获得单选按钮的价值

时间:2011-04-08 01:00:27

标签: javascript asp.net

我在服务器端的运行时创建了单选按钮

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 + "')");
  }

然后在java脚本中我尝试获取单选按钮的值

  function updateQuestions(controlName) {


        var userAnswer;

        if (controlType == "RadioButton") {

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

并且userAnswer为空。我可以得到单选按钮的值???

3 个答案:

答案 0 :(得分:1)

获取value

userAnswer = document.getElementById(controlName).value;

还要考虑将除id之外的内容传递给函数。如果值是您要查找的值,只需传递该值即可。任何这些方法都可以将值直接传递给函数:

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

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

编辑另外,如果您没有在控制服务器端明确设置值,则值空字符串,因此您看到的是正确的。通过转button1.Value = "myValue";创建控件时设置值。

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

答案 1 :(得分:0)

尝试:

userAnswer = document.getElementById(controlName).value;

答案 2 :(得分:0)

更改

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

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