in javascript i can validate a form on submit like below:-
<form action="" method="post" onsubmit="return validate(this)">
<input type="text" name="uName" id="uName" />
<input type="password" name="passKey" id="passKey" />
<input type="submit" name="loginBtn" value="login" />
</form>
<script type="text/javascript">
function validate(loginForm){
if(loginForm.uName.value == ''){
alert('Please Enter Username');
loginForm.uName.focus();
}else if(loginForm.passKey.value == ''){
alert('Please Enter Password');
loginForm.passKey.focus();
}else {
return true;
}
}
</script>
I tried with below jQuery Code
<form action="" method="post">
<input type="text" name="uName" id="uName" />
<input type="password" name="passKey" id="passKey" />
<input type="submit" name="loginBtn" value="login" />
</form>
<script type="text/javascript">
$('form').submit(function(loginForm){
if(loginForm.uName.val() == ''){
alert('Please enter username');
loginForm.uName.focus();
}else if(loginForm.passKey.val() == ''){
alert('Please enter username');
loginForm.passKey.focus();
}else {
return true;
}
return false;
});
</script>
But not works me... please help me...!
like this?
$('#submit').click(function(){
if( $('#uName').val() == ''){
alert('empty');
}
});
http://jsfiddle.net/TTmYk/
the submit form has a typo in my fiddle u might need to fix that
See the Form Fields jQuery Plugin: https://github.com/webarthur/jquery-fields
You can use the plugin as follows:
var form = $('form#id_form').fields();
form.name.val('Arthur');
form.age.hide();
form.description.css('height', 200);
Or this way:
var form = $('form#id_form').fieldValues();
form.name('Arthur');
form.age(29);
form.description('Web developer.');
var name = form.name();
The argument in the submit callback function is not the element instead it is the event. So inside the callback this
represents the form element so you could just do this.uName.value
and you can avoid the use of id as well.
So
$('form').submit(function(e){
if(this.uName.value == ''){
alert('Please enter username');
this.uName.focus();
}else if(this.passKey.value == ''){
alert('Please enter username');
this.passKey.focus();
}else {
return true;
}
return false;
});
Fiddle
Plus val()
is jquery method, and in plain javascript you would use value
and in this case that should be sufficient enough.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With