[英]How can I create two groups of radio buttons in a HTML form and when change in A Group will change in B Group?
I Need to create two forms with radio buttons as following bellow and then, when change checked, I need to change automatically in the second form (jquery or javacript): 我需要按如下所示用单选按钮创建两个表单,然后在选中更改后,我需要在第二个表单(jquery或javacript)中自动进行更改:
<form id="form-a" name="form-a">
<input type="radio" name="name-a" id="id-a" value="Yes" checked="checked" />
<input type="radio" name="name-b" id="id-b" value="No" />
</form>
<form id="form-b" name="form-b">
<input type="radio" name="name-c" id="id-c" value="Yes" checked="checked" />
<input type="radio" name="name-d" id="id-d" value="No" />
</form>
EDIT: Changed the HTML and JS. 编辑:更改了HTML和JS。 Know you just have to add the classes to the Radiobuttons.
知道您只需要将类添加到单选按钮即可。 Tsted with Firefox, Chrome and IE 11. Maybe its not working because jquery is not loaded?
在Firefox,Chrome和IE 11中使用过Tsted。也许由于未加载jquery而导致其不起作用? If you Add jquery in the Javascript-Part, its working.
如果在Javascript-Part中添加jquery,则其工作正常。
My solution is working in both ways. 我的解决方案同时以两种方式工作。 Click on form-a and form-b
单击表格a和表格b
HTML: I changed the button names for grouping. HTML:我更改了用于分组的按钮名称。 JQuery selector is the classname i added.
jQuery选择器是我添加的类名。
<body onload="bodyLoad()">
<form id="form-a" name="form-a">
<input type="radio" class="radioA" name="name-a" id="id-a" value="Yes" checked="checked" />
<input type="radio" class="radioB" name="name-b" id="id-b" value="No" />
</form>
<form id="form-b" name="form-b">
<input type="radio" class="radioA" name="name-c" id="id-c" value="Yes" checked="checked" />
<input type="radio" class="radioB" name="name-d" id="id-d" value="No" />
</form>
JS: I decided to use click event. JS:我决定使用click事件。
function bodyLoad () {
$("input:radio").click(function() {
var myClass = $(this).attr("class");
$("input:radio").prop('checked',false);
$("." + myClass).prop('checked',true);
});}
Just change the name
attribute values on the radio buttons to group them and then just add an event listener to listen for changes. 只需更改单选按钮上的
name
属性值即可将它们分组,然后只需添加事件侦听器即可侦听更改。
Here is an example. 这是一个例子。
var radioBtns = document.querySelectorAll("input[type=radio]"); function radioChangeHndl(evt) { radioBtns.forEach(function(radioBtn) { radioBtn.checked = ''; if(radioBtn.value === this.value) { radioBtn.checked = 'true' } }.bind(this)) } radioBtns.forEach(function(radioBtn) { radioBtn.addEventListener('change', radioChangeHndl); });
<form id="form-a" name="form-a"> <input type="radio" name="name-a" id="id-a" value="Yes" checked="checked" /> <input type="radio" name="name-b" id="id-b" value="No" /> </form> <form id="form-b" name="form-b"> <input type="radio" name="name-c" id="id-c" value="Yes" checked="checked" /> <input type="radio" name="name-d" id="id-d" value="No" /> </form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.