Reputation: 357
I am using this script to see if a user has left any inputs invalid clientside.
$('#login_submit').click(function() {
var login_email = $('#login_email').val();
var login_password = $('login_password').val();
if (login_email.length == 0) {
$('#login_email').css('background', 'red');
}
if (login_password.length == 0) {
$('#login_password').css('background', 'red');
}
});
One thing I cannot work out is how to stop the form submitting as it would. I have tried return false; but this then makes the input fields backgrounds just flicker red.
Regards,
Upvotes: 1
Views: 97
Reputation: 370
Your problem is most likely because you're using a submit button: <input type="submit" ... />
You need to change it to a regular button: <input type="button" ... />
Then in your function you'll need to submit the form when the code is valid: $('#formId').submit();
Upvotes: 0
Reputation: 14435
$('#your-form-id').submit(function() {
var errors = 0;
var login_email = $('#login_email').val();
var login_password = $('login_password').val();
if (login_email.length == 0) {
$('#login_email').css('background', 'red');
errors++;
}
if (login_password.length == 0) {
$('#login_password').css('background', 'red');
errors++;
}
return errors ? false : true;
});
Fiddle demo: http://jsfiddle.net/xjNut/
Just make sure you don't have an input
with name="submit"
in the form. All other attributes are fine to have in the input.
Upvotes: 1
Reputation: 981
do
<input type="submit" onsubmit="return submitValidate()" />
and change your JS to:
function submitValidate() {
var login_email = $('#login_email').val();
var login_password = $('login_password').val();
var submit = true;
if (login_email.length == 0) {
submit = false;
$('#login_email').css('background', 'red');
}
if (login_password.length == 0) {
submit = false;
$('#login_password').css('background', 'red');
}
return submit;
}
Upvotes: 1