简体   繁体   中英

Radio Buttons and javascript, wrong output

below is the code for my radio buttons,

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

and below is my javascript,

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

but I get 'on' on alert, instead of north, south or east. I tried my best but cannot figure out the reason.

Your HTML elements don't have a value attribute set, so you can't get North using .value

If you're trying to get North from the parent label tag, you can access it this way:

JS

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

HTML (note there was a missing " in your question)

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

https://jsfiddle.net/csqgq1qh/

Hope that helps!

EDIT

If you need to get the value of the radio, you first have to assign a value attribute. Once you have that, you can get the checked radio's value using some 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); } )

Updated JSFiddle

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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