haitruonginfotech haitruonginfotech - 6 months ago 27
HTML Question

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 ?

Answer

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