JavaScript string comparison

JavaScript does not provides a method to compare the strings. However, You can use the == operator to compare the strings for equality and for inequality comparison, you will use != operator. In the example below, user name and password input by the user are compared with string "Dara" and "pas123" respectively.

<html>
<head>
<title>string comparison-checking valid input</title>
<script type="text/javascript" language="JavaScript">
function check(){
var usrname=new String(document.getElementById("txtname").value );
var pass=new String(document.getElementById("txtpassword").value );
if( usrname=="Dara" && pass=="pas123"){
document.getElementById("divres"). innerHTML="Valid!";
document.getElementById("divres"). style.color="green";
}
else{
document.getElementById("divres"). innerHTML="Invalid!";
document.getElementById("divres").style.color="red";
}
}

</script>

</head>
<body>

<form action="#">
<table>
<tr>
<td>
<div id="divres"></div>
</td>
</tr>
<tr>
<td>Enter user name:</td><td> <input type="text" id="txtname" ></td>
</tr>
<tr>

<td>Enter password: </td><td><input type="password" id="txtpassword" ></td>
</tr>
<tr>
<td><input type="button" name="submit" value="Submit" onclick="check()"></td>
</tr>
</table>

</form>

</body>
</html>

Posted by: Dara | post date: 03-15-2013 | Subject: JavaScript




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.