Is there a way to populate checkboxes based on a radio button click?

匿名 (未验证) 提交于 2019-12-03 01:44:01

问题:

I have three radio buttons and 17 checkboxes. I would like the radio button that is selected to populate a set of the checkboxes while still giving the user a way to select more if necessary. Is there any way to do this?

回答1:

JavaScript has the power to do this (made far easier by jQuery). You'll want to set an "onClick" function on the radio buttons that can then set the checked value of the checkboxes. For example, this function will turn on/off checkboxs based on what radio button was clicked.

function CheckBoxes(selection) {     if(selection == 1) {         // Checks checkbox with id "CheckBoxID"         $("#CheckBoxID").prop("checked", true);         // Unchecks checkbox with id "CheckBoxID2"         $("#CheckBoxID2").prop("checked", false);     }     else if(selection == 2) {         // Unchecks checkbox with id "CheckBoxID"         $("#CheckBoxID").prop("checked", false);         // Checks checkbox with id "CheckBoxID2"         $("#CheckBoxID2").prop("checked", true);     }     // etc, depending on how many radio buttons and checkboxes you have } 

This function can be called with a radio button by doing:

<input type="radio" id="radio1" name="someName" value="someValue1" onclick="CheckBoxes(1)"> <input type="radio" id="radio2" name="someName" value="someValue2" onclick="CheckBoxes(2)"> <input type="radio" id="radio3" name="someName" value="someValue3" onclick="CheckBoxes(3)"> 

This is just how I'd do it off the top of my head, others will tell you not to assign an OnClick in the html but rather subscribe to it with JavaScript by doing this instead:

$('#radio1').click(function(){CheckBoxes(1)}); 

JSFiddle that shows it off properly.



回答2:

Check this FIDDLE



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!