2

I want a field to become required only when a specific option is selected or a specific radio button is selected or when a specific string is entered in a text input field (All of the required( dependency-expression ) examples I can find assume that the dependency is whether an input is checked / unchecked or filled/unfilled in the case of text fields)

Here is an example of what I need, based on a radio section:

Marital Status (the required field):

<input name="status" id='status'type="radio" value="couple" checked="checked" />
<input name="status" id='status'type="radio" value="single male"  />
<input name="status" id='status'type="radio" value="single female" />

Partners Name (the dependent field - required only when 'Couple' is selected from above)

<input name="partner" type="text"  id="partner">

Example 2: Required field = Venue

<select name="venue" id="venue">
<option value="">Please select venue</option>
<option>London EC1</option>
<option>London E9</option>
<option>Birmingham</option>

etc. Dependent field = user (only required for one of the above selections, say 'Birmingham')

<input name="user" type="text" id="user">

How do I adapt the example shown athttp://docs.jquery.com/Plugins/Validation/Methods/required#dependency-expression for the above situations?

$("#myform").validate({
  rules: {
    details: {
      required: "#other:checked"
    }
  }, debug:true
});
$("#other").click(function() {
  $("#details").valid();
});

I have tried:

user: {
      required: "#venue:('birmingham')"
    }

and

partner: {
      required: "#status:('couple')"
    }

but these have the effect of making user and partner required regardless of results in venue and status

1 Answer 1

5

For the first one, your radio inputs should have different id's:

<input name="status" id='statusCouple' type="radio" value="couple" checked="checked" />
<input name="status" id='statusSingleMale' type="radio" value="single male"  />
<input name="status" id='statusSignleFemale' type="radio" value="single female" /> 

Then your rule can look like this:

partner: {
  required: "#statusCouple:checked"
}

For the second one, just make your rule like this:

user: {
  required: function(element) { return $("#venue").val() == 'Birmingham'; }
}       

Should do the trick.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.