简体   繁体   English

我如何使用 javascript 获得单选按钮的值?

[英]how i get a value on radio button with javascript?

Make my code work please,请让我的代码工作,

 function myFunction() { var x = document.getElementById("myRadio").value; document.getElementById("demo").innerHTML = x; }
 <input type="radio" name="colors" value="-161" id="myRadio">first number <input type="radio" name="s" value="5" id="myRadio">sec number <p>Click the "Try it" button to display the value of the value attribute of the radio button.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p>

Your radio button <input type="radio" value="myValue" id="myRadio" />您的单选按钮<input type="radio" value="myValue" id="myRadio" />

Your Button <button onclick="myFunction()">Try it</button>您的按钮<button onclick="myFunction()">Try it</button>

Run function when button click单击按钮时运行 function

function myFunction() { 
   var x = document.getElementById("myRadio").value; 
   document.getElementById("demo").textContent = x;
}

I believe you want the system to be able to display which radio button is checked and then display the value (-161 or 5) when the button is click.我相信您希望系统能够显示选中了哪个单选按钮,然后在单击按钮时显示值(-161 或 5)。

In that case, you can loop thru the radio buttons to check which one is checked and then get the value.在这种情况下,您可以循环通过单选按钮来检查哪个被选中,然后获取值。

please use the following请使用以下

 function myFunction() { // var x = document.getElementById("myRadio").value; var ele = document.getElementsByName('colors'); for(i = 0; i < ele.length; i++) { if(ele[i].checked){ x=ele[i].value;} } document.getElementById("demo").innerHTML = x; }
 <input type="radio" name="colors" value="-161" id="myRadio">first number <input type="radio" name="colors" value="5" id="myRadio">sec number <p>Click the "Try it" button to display the value of the value attribute of the radio button.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM