Validation in jquery
Only when all the fields are valid take them to the next page
by Varun Krishna P
HTML
<input type="text" class="txt-username"/><br/>
<span class="error error-username"></span><br/>
<input type="txt" class="txt-destination" /><br/>
<span class="error error-dest"></span><br/>
<button class="btn-next" value="next">Next</button>
CSS
.error{
color: #ff0000;
font-weight: bold;
}
JavaScript
valid = true;
$(function(){
$(".txt-username").keyup(function(){
if($(this).val() !=""){
$(".error-username").html("");
valid = true;
}
});
$(".txt-destination").keyup(function(){
$(".error-dest").html("");
if($(this).val() ==""){
$(".error-dest").append("* Please enter the destination");
valid = false;
}else{
valid = true;
if($(this).val().length > 4){
valid = false;
$(".error-dest").append("* The destination value should be less that 4 characters");
}
}
});
$(".btn-next").click(function(){
if($(".txt-username").val() == ""){
$(".error-username").html("");
valid = false;
alert("isValid: "+valid);
$(".error-username").append("* Please enter the username");
}
if($(".txt-destination").val() == ""){
$(".error-dest").html("");
valid = false;
alert("isValid: "+valid);
$(".error-dest").append("* Please enter the destination");
}
if(valid){
alert("isValid: "+valid);
alert("success...");
}
});
});