jquery - show/hide checkboxes based on selected radio button
I am currently developing a small form for an order process.
The form has multiple fields, including input fields and radio/checkboxes.
The current form is as follows:
<form id="order_process" name="order_process" method="post" action="">
<table>
<tr>
<td>
<label for="colour">Colour</label>
</td>
<td>
<label for="small">Small</label>
<input type="radio" name="type" value="Small" />
</td>
<td>
<input type="checkbox" name="colours" value="red" />
<input type="checkbox" name="colours" value="blue" />
<input type="checkbox" name="colours" value="yellow" />
</td>
<td>
<label for="medium">Medium</label>
<input type="radio" name="type" value="Medium" />
</td>
<td>
<input type="checkbox" name="colours" value="orange" />
<input type="checkbox" name="colours" value="blue" />
<input type="checkbox" name="colours" value="green" />
</td>
<td>
<label for="large">Large</label>
<input type="radio" name="type" value="Large" />
</td>
<td>
<input type="checkbox" name="colours" value="black" />
<input type="checkbox" name="colours" value="white" />
<input type="checkbox" name="colours" value="red" />
</td>
</tr>
</table>
</form>
What I need to do, is only show the colours
checkboxes if i select a particular radio button. So these checkboxes need to be hidden on page load and only display based on the radio selected.
I know I can achieve this usin开发者_高级运维g jQuery, but I'm not sure how I'd do it.
Many thanks
First have the rows containing the checkboxes hidden and all you need thereafter is this:
var lastRow = null;
$(":radio[name='type']").click(function(){
if (lastRow != null){
lastRow.toggle();
}
lastRow = $(this).parent().next();
lastRow.toggle();
});
This will show the row of checkboxes associated to it. It will also hide any previously open rows for a different radio button that had been clicked.
You can try it out here:
http://jsfiddle.net/jXrxW/
There are many ways to do this with jQuery, but the essence is that you should hide all the checkboxes ($('input type["checkbox"]')
) in $(document).ready
, and then bind click
events to the radio buttons ($('input type["radio"]')
), which show the relevant items. You could make this easy by adding rel values to the checkboxes to indicate which radio button should show them.
Another solution is to add classes to your checkboxes, like this :
<td>
<label for="small">Small</label>
<input type="radio" name="type" value="Small" />
</td>
<td>
<input type="checkbox" class="Small" name="colours" value="red" />
<input type="checkbox" class="Small" name="colours" value="blue" />
<input type="checkbox" class="Small" name="colours" value="yellow" />
</td>
And then, add a change()
listener on your radio buttons, and show()
the corresponding checkboxes :
$(":input[name=type]").change(function() {
var value = $(this).val();
$("input[type=checkbox]:not(." + value + ")").hide();
$("input[type=checkbox]." + value).show();
});
jsFiddle example here
精彩评论