Reputation: 395
I've been looking for a solution to disable the form submit button until the required fields are filled. I've found something here at stackoverflow (courtesy of mblase75), but it's for standard jQuery and doesn't work with jQuery Mobile.
The reason behind this is that there's a form on a mobile page that requires all fields to be filled before submitting it. Validation is solved via php so it's not a necessary part.
$(document).ready(function() {
$form = $('#formid'); // cache
$form.find(':input[type="submit"]').prop('disabled', true); // disable submit btn
$form.find(':input').change(function() { // monitor all inputs for changes
var disable = false;
$form.find(':input').not('[type="submit"]').each(function(i, el) { // test all inputs for values
if ($.trim(el.value) === '') {
disable = true; // disable submit if any of them are still blank
}
});
$form.find(':input[type="submit"]').prop('disabled',disable);
});
});
Sadly I'm not a jQuery guru, and if possible I'd like some help with this. Also any other suggestions are welcome (even for validation with jQuery mobile).
Upvotes: 1
Views: 3113
Reputation: 1898
$(function() {
var form = $('#formid');
var submitBtn = $('#submitBtnId');
submitBtn.addClass('disable');
form.submit(function()
if(validate()) {
submitBtn.removeClass('disable');
}
if(submitBtn.hasClass('disable')) {
return false;
}
else {
return true;
}
});
function validate() {
form.find('input, textarea').change(function(){
// validation goes here if all inputs are validate then return true otherwise false
});
}
});
Upvotes: 1
Reputation: 3485
You may actually be checking the values of other "buttons" like input[type="button"] or input[type="reset"]. These have a blank value unless they are set. The following code accounts for this (plus a few more caching statements):
$(document).ready(function() {
var $form = $('#formid'), // cache
$inputs = $form.find(':input'), // MOD extra caching
$buttons = $inputs.not(':submit, :reset, :button'),
$fields = $inputs.not($buttons),
$submits = $buttons.filter(':submit');
$submits.prop('disabled', true); // disable submit btn
$fields.keyup(function() { // monitor all inputs for changes, MOD changed to keyup
var disable = false;
$fields.each(function(i, el) { // test all inputs for values
if ($(el).val() === '') { // MOD use jQuery to get value
disable = true; // disable submit if any of them are still blank
return false; // MOD stop "each" if even one field is blank... less waste
}
});
$submits.prop('disabled',disable);
});
});
This will not account for a group of radio buttons where none were checked, however.
Upvotes: 0