问题
I am using the jquery validate plugin for the first time. I am in a situation where I have a select box that has three options. I need to do two things:
- Make the select box required.
- Depending on the option selected, make other text boxes required.
So...
<select id="selectBox">
<option value selected></option>
<option value="1">1</option>
<option value="2">2</option>
<option Value="3">3</option>
</select>
Coord 1: <input type="text" name="coord1"><br>
Coord 2: <input type="text" name="coord2"><br>
Coord 3: <input type="text" name="coord3"><br>
- If option 1 is selected on the dropdown, Coord 1 is required.
- If option 2 is selected, Coords 1 and 2 are required.
- If option 3 is selected, Coord 1 and Coord 3 are required.
How does this work adding custom rules to the validator?
Thanks in advance...
回答1:
try
If you need starting itself
// $('input[type=text]:eq(0)').prop('required', true);
$("#selectBox").change(function () {
var index=this.value-1;
$('input[type=text]:gt(0)').prop('required', false);
// $('input[type=text]:eq(0)').prop('required', true);
$('input[type=text]:eq('+index+')').prop('required', true);
});
DEMO
来源:https://stackoverflow.com/questions/25286616/adding-validation-rules-depending-on-option-selected-from-dropdown-menu