I'm trying to figure out how to validate a form element with a mix of radio inputs and a text input:
<label>Question?</label>
<input type="radio" class="mandatory" name="questions[1][]" value="1" />answer 1<br/>
<input type="radio" class="mandatory" name="questions[1][]" value="2" />answer 2<br/>
<input class="ignore" type="radio" id="questions[1][]" />Other (please specify)<br/>
<input class="optional mandatory" type="text" name="questions[1][]" value="" />
I've figured out how to get the form to behave as expected (select and unselect) with the following code:
$("input.optional").focus(function () {
var this_name = $(this).attr("name");
$("input:radio").filter(function() {return $(this).attr('name') == this_name; }).attr('checked', false);
$("input").filter(function() {return $(this).attr('id') == this_name; }).attr('checked', true);
});
$(':radio').click(function () {
var this_name = $(this).attr("name");
$("input").filter(function() {return $(this).attr('id') == this_name; }).attr('checked', false);
$("input.optional").filter(function() {return $(this).attr('name') == this_name; }).val('');
});
I was hoping I could use the class "mandatory" to validate the mix of radio and text inputs:
$("form .manditory").each(function () {
$(this).rules("add", {required: true});
});
But it's not working as expected. With the radio (id="questions[1][]") selected, and the text input containing content, the form element is still flagged as invalid.
Suggestions...maybe a better approach?
Thanks in advance.
UPDATE
Sorry, I should have clarified that I'm using the validate plugin:
$("form").validate({ ... });