[英]Getting selected value for radio button
<!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的單選按鈕獲取價值的基本示例。 在上面的示例中,我需要獲取顯示值。
例如,我需要Red color
不是red
值。 這里的例子
與其僅將文本包裝在標簽中,不如使它有用
<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
。
對於獎勵積分,您現在可以單擊“紅色”文本以選擇單選按鈕。 可用性真棒!
好多了。
您應該將該文本包裝在label
以幫助定位,並找到.nextElementSibling
的.innerHTML
。
var x = document.getElementById("myRadio").nextElementSibling.innerHTML;
document.getElementById("demo").innerHTML = x;
您可以將文本包裝在標簽標簽中,然后使用nextSibling.innerHTML
在標簽內獲取文本。
添加標簽:
<input type="radio" name="colors" value="red" id="myRadio" /><label>Red color</label>
然后使用nextSibling.innerHTML
代替value
:
var x = document.getElementById("myRadio").nextSibling.innerHTML;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.