Hare Kumar
Hare Kumar

Reputation: 719

Accessing the radio button value

Html Code: -

<input type="radio" name="radio" id="radio" value="1" onclick="validate()"> For Yourself</input> </p></br>
    <p>
    <input type="radio" name="radio" id="radio" value="2" onclick="validate()"> For Users</input>
    </p>

And JavaScript Code : -

function validate()
    {
        var btn_value=document.getElementById("radio").value;
        if(btn_value==true)
        {
            alert(btn_value);
        }

    }

Now, whenever I am trying to print the value of radio button. It is always printing value as 1.

So, Now I don't understand what exactly am I missing here...

Thanx in advance for your help.

Upvotes: 0

Views: 101

Answers (4)

silly
silly

Reputation: 7887

first of all never use a DOMID twice in your html! remove them.... only use dublicated names!

<input type="radio" name="radio" value="1" onclick="validate()"> For Yourself</input> </p></br>
<p>
<input type="radio" name="radio" value="2" onclick="validate()"> For Users</input>
</p>

with the js check every element with the name attribute!

function validate() {
    var elements = document.getElementsByName("radio");
    for(var n = 0; n < elements.length; n++) {
        if(elements[n].checked === true) {
            alert(elements[n].value);
        }
    }
}

if you use your validate method ONLY in the onclick you can pass the domelement in the validate methode like this:

<input type="radio" name="radio" value="1" onclick="validate(this)"> For Yourself</input> </p>

and your js:

function validate(domElement) {
     if(domElement.checked === true) {
            alert(elements[n].value);
        }
}

Upvotes: 1

NinaNa
NinaNa

Reputation: 1647

  1. IDs MUST be unique, it's a mistake to give it the same id.
  2. You can give the IDs a running number (- radio1,radio2 etc) and loop through them to check which one was selected.

Upvotes: 0

Muthu Kumaran
Muthu Kumaran

Reputation: 17930

Elements ID should be unique. I modified your HTML and JS part and check below

Try this

HTML

<p>
     <input type="radio" name="radio" id="radio1" value="1" onclick="validate(this)"> For Yourself</input> </p></br>
<p>
    <input type="radio" name="radio" id="radio2" value="2" onclick="validate(this)"> For Users</input>
</p>

JavaScrpit

function validate(obj)
    {
        var btn_value=obj.value;
        if(btn_value==true)
        {
            alert(btn_value);
        }

    }

Upvotes: 2

Pragnesh Chauhan
Pragnesh Chauhan

Reputation: 8476

try this

<input type="radio" name="radio" id="radio" value="1" onclick="validate(this)"> For Yourself</input> </p></br>
<p>
<input type="radio" name="radio" id="radio" value="2" onclick="validate(this)"> For Users</input>
</p>​

function validate(ele)
{
    alert(ele.value);
}​

Upvotes: 0

Related Questions