Mohammed Thabet
Mohammed Thabet

Reputation: 21667

get value of radio button

I created radio button at runtime in server side

RadioButton button1 = new RadioButton();
button1.ID = question.Name + "_Radio1";
button1.Text = "Yes";

RadioButton button2 = new RadioButton();
button2.ID = question.Name + "_Radio2";
button2.Text = "No";
 if (question.IsDynamic)
 {
     button1.Attributes.Add("onclick", "return updateQuestions('" + button1.ID + "')");
  }

then at java script I try to get the value of radio button

  function updateQuestions(controlName) {


        var userAnswer;

        if (controlType == "RadioButton") {

            userAnswer = document.getElementById(controlName).innerHTML;
        }

and userAnswer is empty .how can I get the value of radio button???

Upvotes: 0

Views: 2084

Answers (3)

gilly3
gilly3

Reputation: 91467

Get value:

userAnswer = document.getElementById(controlName).value;

Also consider passing something besides id into the function. If the value is what you are looking for, just pass the value. Any of these approaches will work to pass the value directly to the function:

button1.Attributes.Add("onclick", "return updateQuestions('someValue')");

or

button1.Attributes.Add("onclick", "return updateQuestions(this.value)");

Edit: Also, if you aren't explicitly setting the value on the control server side, the value is empty string, so what you are seeing is correct. Set the value when you create the control by going button1.Value = "myValue";.

RadioButton button1 = new RadioButton();
button1.ID = question.Name + "_Radio1";
button1.Text = "Yes";
button1.Attributes["value"] = "Yes";

Upvotes: 1

ysrb
ysrb

Reputation: 6740

Change

button1.Attributes.Add("onclick", "return updateQuestions('" + button1.ID + "')"); to

button1.Attributes.Add("onclick", "return updateQuestions('" + button1.ClientID+ "')");

Upvotes: 0

Šime Vidas
Šime Vidas

Reputation: 185873

Try:

userAnswer = document.getElementById(controlName).value;

Upvotes: 0

Related Questions