单选按钮和javascript,输出错误

时间:2016-05-11 18:10:27

标签: javascript html5

下面是我的单选按钮的代码,

<label class="radio-inline">
<input type="radio" name="optradio"  id="radio_north autocomplete='off'>North
</label>
<label class="radio-inline">
<input type="radio" name="optradio"  id="radio_south" autocomplete='off'>South
</label>
<label class="radio-inline">
<input type="radio" name="optradio"  id="radio_east" autocomplete='off'>East
</label>

以下是我的javascript,

var form = document.getElementById("info_form");
alert(form.elements["radio_north"].value);

但是我警惕地“开启”,而不是北,南或东。我尽我所能,但无法弄清楚原因。

1 个答案:

答案 0 :(得分:0)

您的HTML元素没有设置value属性,因此您无法使用.value

进入北方

如果您尝试从父标签标签获取North,则可以通过以下方式访问它:

<强> JS

var form = document.getElementById("info_form");
console.log(form.querySelector("#radio_north").parentNode.innerText);

HTML (请注意您的问题中缺少"

<form id="info_form">
    <label class="radio-inline">
        <input type="radio" name="optradio"  id="radio_north" value="north" autocomplete='off'>North
    </label>
    <label class="radio-inline">
        <input type="radio" name="optradio"  id="radio_south" autocomplete='off'>South
    </label>
    <label class="radio-inline">
        <input type="radio" name="optradio"  id="radio_east" autocomplete='off'>East
    </label>
</form>

JS小提琴示例

https://jsfiddle.net/csqgq1qh/

希望有所帮助!

修改

如果您需要获取广播的值,首先必须指定value属性。完成后,您可以使用一些JavaScript获取已检查的无线电值。

<强> HTML

<form id="info_form">
    <label class="radio-inline">
        <input type="radio" name="optradio"  id="radio_north" value="north" checked autocomplete='off'>North
    </label>
    <label class="radio-inline">
        <input type="radio" name="optradio"  id="radio_south" value="south" autocomplete='off'>South
    </label>
    <label class="radio-inline">
        <input type="radio" name="optradio"  id="radio_east" value="east" autocomplete='off'>East
    </label>
</form>
<button id="clicker">Get Value</button>

<强> JS

var form = document.getElementById("info_form");
console.log(form.querySelector("input[name='optradio']:checked").value);

/* use an event listener to alert the value when the button is clicked */
document.querySelector("#clicker").addEventListener('click', function() { alert(form.querySelector("input[name='optradio']:checked").value); } )

更新了JSFiddle

https://jsfiddle.net/csqgq1qh/2/