document.querySelector('input[name=nameOfradio]:checked').值;但收音机未检查

document.querySelector('input[name=nameOfradio]:checked').value; but radio not checked

我正在尝试通过以下方式从收音机中获取值: document.querySelector('input[name=nameOfradio]:checked').value;

但即使检查了 none 个收音机,我也想获得一个值。

例如,在这个片段中,如果两个收音机都没有被选中,我想将文本更改为“你没有 select a number and you didn't select a字母

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>

您可以在使用以下语法请求值之前检查是否存在:

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>