I'm trying to get the value from a radio with:
document.querySelector('input[name=nameOfradio]:checked').value;
But I want to get a value even if none of the radios are checked.
For example in this snippet, if neither of the radios are checked I'd like to change the text for "you didn't select a number and you didn't select a letter"
function myFunction(){
let var1 = document.querySelector("input[name=radioa]:checked").value;
let var2 = document.querySelector("input[name=radiob]:checked").value;
document.getElementById("change").innerHTML = var1 " and " var2;
}
<div>
<p>Which number will you choose ?</p>
<input id="one" name="radioa" type="radio" value="Number 1"/>
<label for="one">The N° 1</label>
<input id="two" name="radioa" type="radio" value="Number 2"/>
<label for="two">The N° 2</label>
</div>
<div>
<p>Which letter will you choose ?</p>
<input id="a" name="radiob" type="radio" value="Letter a"/>
<label for="a">The letter a</label>
<input id="b" name="radiob" type="radio" value="Letter b"/>
<label for="b">The lettter b</label>
</div>
<div>
<button id="z" onclick="myFunction();">button</button>
</div>
<div>You have chosen :</div>
<div id="change"></div>
CodePudding user response:
You can check for the existence before asking for the value with this syntax:
document.querySelector("input[name=radioa]:checked")?.value
function myFunction() {
let var1 = document.querySelector("input[name=radioa]:checked")?.value;
let var2 = document.querySelector("input[name=radiob]:checked")?.value;
if (var1 && var2) output = var1 " and " var2;
else output = "Please select both a number and a letter";
document.getElementById("change").innerHTML = output;
}
<div>
<p>Wich number will you choose ?</p>
<input id="one" name="radioa" type="radio" value="Number 1" />
<label for="one">The N° 1</label>
<input id="two" name="radioa" type="radio" value="Number 2" />
<label for="two">The N° 2</label>
</div>
<div>
<p>Wich letter will you choose ?</p>
<input id="a" name="radiob" type="radio" value="Letter a" />
<label for="a">The letter a</label>
<input id="b" name="radiob" type="radio" value="Letter b" />
<label for="b">The lettter b</label>
</div>
<div>
<button id="z" onclick="myFunction();">button</button>
</div>
<div>You have chosen :</div>
<div id="change"></div>