Reputation: 3
how can I set presets for radio buttons with jQuery?
Here is a simple example: http://jsfiddle.net/EpQgr/
<select>
<option>option 1</option>
<option>option 2</option>
</select>
<div>
<input id="radio1_0_0" type="radio" name="radio1" value="1" />x
<input id="radio1_0_1" type="radio" name="radio1" value="2" />y
<input id="radio1_0_2" type="radio" name="radio1" value="3" />z
</div>
<div>
<input id="radio2_0_0" type="radio" name="radio2" value="1" />x
<input id="radio2_0_1" type="radio" name="radio2" value="2" />y
<input id="radio2_0_2" type="radio" name="radio2" value="3" />z
</div>
The pre set options should be something like this:
//option 1
$("#radio1_0_1, #radio2_0_2").prop("checked",true);
//option 2
$("div input:first-child").prop("checked",true);
Upvotes: 0
Views: 372
Reputation: 123397
change your html code in this way:
<select>
<option value="">Choose a preset</option>
<option value="#radio1_0_1, #radio2_0_2">option 1</option>
<option value="#radio1_0_0, #radio2_0_0">option 2</option>
</select>
and the JS
$('select').on('change', function() {
var v = $(this).val();
if ($(v).length) {
$(v).prop("checked", true);
}
});
The elements to check are stored inside value
attribute of each option.
This solution avoids having to enter each preset inside the handler of the select. If you need to insert a new preset just add the option with a new selector
see jsfiddle: http://jsfiddle.net/8f7Nw/2/
Upvotes: 1
Reputation: 75103
You probably want the dropdow to be used to select the radio options
try this:
$("select").bind("change", function() {
// un select all
$("input[type=radio]").prop("checked",false);
if($(this).val() === "option 1") {
//option 1
$("#radio1_0_1, #radio2_0_2").prop("checked",true);
}
if($(this).val() === "option 2") {
//option 2
$("div input:first-child").prop("checked",true);
}
});
Your fiddle updated
Upvotes: 0