Reputation: 2893
I have a simple form
<form role="form" id="my_form" class="form-horizontal">
<label class="radio">
<input type="radio" name="reason[]" id="reasonOne" value="1"> Something
</label>
<label class="radio">
<input type="radio" name="reason[]" id="reasonTwo" value="2"> Something else
</label>
<label class="radio">
<input type="radio" name="reason[]" id="reasonThree" value="Other"> Other
</label>
<input type="text" name="reason[]" placeholder="Please specify" id="other" class="form-control">
</form>
The bottom radio controls a text input. Initially this is hidden, and I do
$('input:radio[name="reason[]"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == 'Other') {
$('#other').css("display", 'block');
} else {
$('#other').css("display", 'none');
}
}
);
Defining rules for radio buttons is straight forward, I just need to make sure one is selected. I am having a few issues with a custom rule. Essentially, if reasonThree is selected, I need to make sure they enter something into the text input which is at this point displayed. At this moment, I am trying something like the following.
jQuery.validator.addMethod('customrule', function() {
if($("input[id='reasonFive']:checked")) {
if(('#other').val().length == 0) {
return false;
} else {
return true;
}
}
return false;
}, 'Please input a reason' );
var validator = $("#my_form").validate({
rules: {
'reason[]': {
required: true,
customRule: true
}
},
messages: {
'reason[]': {
required: jQuery.validator.format("Please select an option")
}
}
});
If they select the last radio button, how can I make sure they enter something into the text area?
Thanks
Upvotes: 1
Views: 5300
Reputation: 10659
There is no element with id [id='reasonFive']
. Try to change your custom method like this:-
$.validator.addMethod("customRule",function(value,element){
if($('#reasonThree').is(':checked')){
return $('#other').val().trim().length>0;
}else{
return true;
}
},"Please input a reason");
Upvotes: 3