Reputation: 157
I want to select only one option in a radio element, I made it work but my solution is kinda dumb. How can I do it better.
function check1(){
var p1 =document.getElementById("PMLN");
var p2 =document.getElementById("PMLA");
var p3 =document.getElementById("PMLAD");
if(p1.checked == true & p2.checked == false & p3.checked==false){
console.log('press 1');
}
if(p2.checked == true & p1.checked == false & p3.checked==false){
console.log('press 2');
}
if(p3.checked == true & p2.checked == false & p1.checked==false){
console.log('press 3');
}
}
<h3>Tractor 1</h3>
<input type="radio" name="Tractors" id="PMLN"/>
<h3>Tractor 2</h3>
<input type="radio" name="Tractors" id="PMLA"/>
<h3>Tractor 3</h3>
<input type="radio" name="Tractors" id="PMLAD" />
<br><br>
<button onclick="check1()">Try it</button>
Upvotes: 0
Views: 72
Reputation: 180
Taken from Geeks For Geeks
Due to the nature of radio buttons, only one can be selected as long as the "name" attribute is the same between the buttons. To figure out which one is currently selected, you can get all of the elements with that name, and iterate over them, checking which value is true.
Example (vanilla javascript):
let ele = document.getElementsByName('Tractors');
for(let i = 0; i < ele.length; i++) {
if(ele[i].checked) {
console.log(`Pressed ${ele[i]}`);
}
}
Or using jQuery:
$("input[name='Tractors']:checked").val();
Upvotes: 1