JavaScript tutorial-String object length property

JavaScript String object: length property

The length property can be used to count the number of characters in a string object. It is much like that you count the number of elements in an array object. In the example below we use the length property to check whether the user entered the correct length of password field that is greater than 8 characters.


<title>Text field element</title>
<script type="text/javascript" language="JavaScript">
function login(){
var user=document.forms[0].username.value;//get value from the username tex box
var pass=document.forms[0].password.value;//get value from the password text box
document.getElementById("mydiv").style.backgroundColor="509877"; // set div background color

var p=new String(pass);
if(p.length>=8) //checking the length of the password field
document.getElementById("mydiv").innerHTML="<strong>Welcome "+user+"!</strong><br>"+ "Your password is "+ pass+"."; //Display welcome message in the div tag
else {
document.getElementById("mydiv").innerHTML="<strong>The password length must be greater than 8 characters.</strong>"; //Display error message
document.getElementById("mydiv").style.backgroundColor="red"; // set div background color
//in the form of html code that can be translated by browser.

<form action="#">
<td>User name:</td><td> <input type="text" name="username" ></td>
<td>E-mail: </td><td><input type="text" name="password" ></td>
<td><input type="button" name="submit" value="submit" onclick="login()"></td>
<div id="mydiv"></div>


This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.