我正在尝试通过以下方式从收音机获取值:
document.querySelector('input[name=nameOfradio]:checked').value;
但即使没有检查任何无线电,我也想获得一个值。
例如在这个片段中,如果两个收音机都没有被选中,我想更改文本“您没有选择数字,也没有选择字母”
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>
很好,工作正常,但是我在添加 console.log 时遇到问题,nodejs 中没有响应。 怎么做?
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;
//added code
console.log(output) // this line get no respond
}