简体   繁体   中英

How to get value from form input type=radio?

<input type="radio" value="0" name="type" checked="yes" />
<label>Type 0</label>
<input type="radio" value="1" name="type" />
<label>Type 1</label>

and js:

var type = this.type.value;
alert(type);

How to fix it ?

In what context does that JS code run? If this is the radio button in question then this.value will return the value.

If your question is "How do I get the value of the currently selected radio button in the 'type' group?" then you may need to do something like this:

function getCheckedRadioValue(radioGroupName) {
   var rads = document.getElementsByName(radioGroupName),
       i;
   for (i=0; i < rads.length; i++)
      if (rads[i].checked)
          return rads[i].value;
   return null; // or undefined, or your preferred default for none checked
}

var checkedValue = getCheckedRadioValue("type");

(It would be easier with .querySelector() or .querySelectorAll() , but not all browsers support them.)

Just use selectors.

With jquery

$("input[name=type]:checked").val();

Or without jquery:

document.querySelector("input[name=type]:checked").value;

Just use this.value instead of this.type.value .

this.value will select the value associated with the value attribute of the input. (That's a mouthful).

Using jQuery you can do like this

   $(function() {
        $(".rad").click(
        function() {
             alert(this.value);
        });
    });

See this JSFiddle

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