简体   繁体   中英

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):

<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. 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? If you Add jquery in the Javascript-Part, its working.

My solution is working in both ways. Click on form-a and form-b

HTML: I changed the button names for grouping. JQuery selector is the classname i added.

<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.

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.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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