Reputation: 189
I have two radio buttons as bellow:
<label for="male">Male<br>
<input type="radio" name="gender" id="male" value="male"><br>
<input type="radio" name="gender1" id="male" value="male1"><br>
</label>
How can I checked both of them by click on just one? For example click on first radio and checked first and second one
Upvotes: 0
Views: 55
Reputation: 29282
You can attach a click listener on parent element of both radio inputs and whenever any of the radio input is clicked, you check all of them via javascript
const container = document.getElementById('container');
const radioInputs = document.querySelectorAll('input[type=radio]')
container.addEventListener('click', (e) => {
radioInputs.forEach(i => i.checked = true);
});
<div id="container">
<label for="male">Male<br>
<input type="radio" name="gender" id="male" value="male"><br>
<input type="radio" name="gender1" id="male1" value="male1"><br>
</label>
</div>
Side Note: id of each element should be unique. You should not use id on both radio inputs
Upvotes: 1
Reputation: 68933
The attribute id must be unique in a document, use class instead. On clicking any button you can set the checked attribute to true:
$('.male').click(function(){
$('.male').attr('checked', true);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="male">Male<br>
<input type="radio" name="gender" class="male" value="male"><br>
<input type="radio" name="gender1" class="male" value="male1"><br>
</label>
Upvotes: 1
Reputation: 27381
Each id can only be used once per page. So I changed it to male1 and male2.
let male1 = document.querySelector("#male1");
let male2 = document.querySelector("#male2");
male1.addEventListener("input", () => {
male2.checked = "true";
});
male2.addEventListener("input", () => {
male1.checked = "true";
});
<label for="male">Male<br>
<input type="radio" name="gender" id="male1" value="male"><br>
<input type="radio" name="gender1" id="male2" value="male1"><br>
</label>
Upvotes: 1