Reputation: 1918
I am new to jQuery and I have the following lines of jQuery. My intention is 'on submit' to check if the input text values are filled and check to see if the radio buttons are checked or selected and make the text red if they aren't but i am not sure on how to combine the two.
Right now it is kind of buggy because it submits IF the text is filled and it ignores the radio buttons BUT it makes the text red before it submits. so it is working just not how I would like it to.
jQuery
$('#form3096').submit(function (e) {
if (!$('#check-sm input:text').filter(function () {
return $.trim(this.value) != ""
}).length) {
$('.social-heading').css('color','red');
}
});
$('#form3096').submit(function(e) {
if ($('input:radio', this).is(':checked')) {
// everything's fine...
} else {
$('.radio-options').css('color','red');
}
});
Upvotes: 0
Views: 51
Reputation: 990
$('#form3096').submit(function (e) {
if (!$.trim($('#check-sm input:text').val()) {
$('.social-heading').css('color','red');
return false;
}
if ($('input:radio', this).is(':checked')) {
// everything's fine...
return true;
} else {
$('.radio-options').css('color','red');
return false;
}
});
Upvotes: 0
Reputation: 9262
I like to separate my validations into single units and combine them at the end. It makes it easier to read, maintain and test.
$('#form3096').submit(function (e) {
var isFieldPopulated, isRadioChecked;
isFieldPopulated = $('#check-sm input:text').filter(function () {
return $.trim(this.value) !== "";
}).length > 0;
if (!isFieldPopulated) {
$('.social-heading').css('color','red');
}
isRadioChecked = $('input:radio', this).is(':checked');
if (!isRadioChecked) {
$('.radio-options').css('color','red');
}
return isFieldPopulated && isRadioChecked;
});
Upvotes: 1
Reputation: 801
you can try this
$('#form3096').submit(function (e) {
var len = $('#check-sm input:text').filter(function () {
return $.trim(this.value) != ""
}).length;
if (!len) {
$('.social-heading').css('color','red');
e.preventDefault();
}
if(!$('input:radio', this).is(':checked')){
$('.radio-options').css('color','red');
e.preventDefault();
}
});
Upvotes: 0
Reputation: 780724
Call e.preventDefault()
to prevent the normal form submission.
$('#form3096').submit(function (e) {
if (!$('#check-sm input:text').filter(function () {
return $.trim(this.value) != ""
}).length) {
$('.social-heading').css('color','red');
e.preventDefault();
}
});
$('#form3096').submit(function(e) {
if ($('input:radio', this).is(':checked')) {
// everything's fine...
} else {
$('.radio-options').css('color','red');
e.preventDefault();
}
});
Upvotes: 2