haitruonginfotech haitruonginfotech - 2 years ago 101
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;

How to fix it ?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download