繁体   English   中英

如何在HTML表单中创建两组单选按钮,并且当A组中的更改将在B组中更改时?

[英]How can I create two groups of radio buttons in a HTML form and when change in A Group will change in B Group?

我需要按如下所示用单选按钮创建两个表单,然后在选中更改后,我需要在第二个表单(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>

编辑:更改了HTML和JS。 知道您只需要将类添加到单选按钮即可。 在Firefox,Chrome和IE 11中使用过Tsted。也许由于未加载jquery而导致其不起作用? 如果在Javascript-Part中添加jquery,则其工作正常。

我的解决方案同时以两种方式工作。 单击表格a和表格b

HTML:我更改了用于分组的按钮名称。 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:我决定使用click事件。

function bodyLoad () {
$("input:radio").click(function() {
       var myClass = $(this).attr("class");
       $("input:radio").prop('checked',false);
       $("." + myClass).prop('checked',true);
});}

只需更改单选按钮上的name属性值即可将它们分组,然后只需添加事件侦听器即可侦听更改。

这是一个例子。

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM