Long time listener, first time caller…
I've got two questions in a form, the first of which is a 'Yes' or 'No' pair of radio buttons:
"Have you filed an application with us before? ( ) Yes ( ) No"
…the second of which is a text input allowing for a sloppy date value:
"If yes, when did you apply? [__________]"
You might already see where I'm going with this … I only want the second question to be required if "Yes" was chosen from among the radio buttons.
I've done a bunch of Google'ing, searching jQuery's site (not fun or easy), and searching this very fine site, but the closest I've come to an answer always appears to make use of unique ID attributes on the radio inputs.
Sadly, I'm in a situation where the radio inputs can't have ID attributes because they're generated by a CMS. So, I'm left trying to use the unique name attribute on the pair of radio inputs, along with checking if the one with a value of Yes is 'selected'/'checked'.
Here's my HTML:
<li>
<span class="reqField">*</span> Have you filed an application with us before?<br />
<label class="radioInput"><input type="radio" name="app_prior_app" value="Yes" /> Yes</label>
<label class="radioInput"><input type="radio" name="app_prior_app" value="No" /> No</label>
</li>
<li>
<label for="app_prior_app_date">If <em>yes</em>, when did you apply?</label><br />
<input type="text" name="app_prior_app_date" value="" size="40" id="app_prior_app_date" />
</li>
And here's my JS so far:
app_prior_app: "required",
app_prior_app_date: {
required: function(element) {
return $("[name=app_prior_app]").val() == "Yes";
}
}
Naturally this doesn't work as desired. I know that if I could toss IDs on each radio input, this would be easier on me (I'm not too good with this stuff), but I'm assuming there's a way to do this using just th开发者_开发技巧e unique name attribute and determining if the value "Yes" is the one selected, then (and only then) go ahead and require the text input?
A simple modification you can do to get what you need might look something like so:
app_prior_app: "required",
app_prior_app_date: {
required: function() {
return $("input[name=app_prior_app]:checked").val() === "Yes";
}
}
Make sure you run app_prior_app_date.required()
whenever the app_prior_app
radio buttons are changed, though, so the script can maintain the correct state whatever a user does on the page.
If you were to use jquery you could do something like this:
var input_radio = $('input[name="app_prior_app"]:checked').val();
to determine if it is checked and the value. If input_radio == "yes"
then you would probably .hide()
or .show()
the next question
精彩评论