gpt4 book ai didi

javascript - 获取单选按钮的选定值

转载 作者:行者123 更新时间:2023-11-30 10:08:32 26 4
gpt4 key购买 nike

<!DOCTYPE html>
<html>
<body>

<input type="radio" name="colors" value="red" id="myRadio">Red color

<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>

<script>
function myFunction() {
var x = document.getElementById("myRadio").value;
document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

从 w3schools 的单选按钮获取值的基本示例。在上面的示例中,我需要获取显示值。

例如,我需要红色

不是值 redExample here

最佳答案

与其将文本包装在标签中,不如使其有用

<label>
<input type="radio" name="colors" value="red" id="myRadio" />
Red Colour
</label>

现在您的代码可以做到这一点:

function myFunction() {
var radio = document.getElementById("myRadio"),
label = radio.parentNode,
text = (label.textContent || label.innerText).replace(/^\s+|\s+$/g,"");
document.getElementById("demo").innerHTML = text;
}

这将获取单选按钮的父项(标签),获取其文本内容,去除其前后的空格,并输出结果:Red Colour

对于奖励积分,您现在可以单击“红色”文本以选择单选按钮。可用性真棒!

好多了。

关于javascript - 获取单选按钮的选定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27822673/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com