在HTML中,使用Javascript,创建新的单选按钮及其文本?

时间:2014-05-02 14:23:56

标签: javascript html forms javascript-events

我想要的是"是"检查表单(form1)的单选按钮,出现一个新表单(form2),带有两个单选按钮及其文本"是"和"不"。通过活动" onclick"在"是" form1的按钮,我设法使用两个单选按钮显示新表单,但我无法显示他们的文本。由于单选按钮没有" innerHTML",我尝试将文本作为纯文本添加为​​"标签",但它不起作用。 这是语法或逻辑中的问题(不可能与按钮同时创建文本)?谢谢你的帮助。

在我的HTML正文中,我有这个:

<form id="form1">
<input type="radio" id= "form1_no" value="no" checked>
   <label for = "form1_no" >No</label>
<input type="radio" id= "form1_yes" value="yes" onClick= exam()>
   <label for = "form2_yes" >Yes</label>
</form> 

功能考试()是:

<script type='application/javascript'>

function exam() {                  

    var inputno = document.createElement("input");
    inputno.type = "radio";
    inputno.id = "form2_no";
    inputno.value = "no";
    inputno.onclick = function () {alert("I select No in Form 2")}; 
    document.getElementById("form2").appendChild(inputno); // this is working

    var inputyes = document.createElement("input");
    inputyes.type = "radio";
    inputyes.id = "form2_yes";
    inputyes.value  ="yes";
    inputyes.onclick = function () {alert("I select Yes in Form 2")};
    document.getElementById("form2").appendChild(inputyes); // this is working

    // now, the code that is not working:

    // 1st tentative (adding "Yes" and "No" as plain text after their radio button):
    var textno = "No";
       document.getElementById("form2_no").appendChild(textno);
    var textyes = "Yes";
       document.getElementById("form2_yes").appendChild(textyes);

    // 2nd tentative (adding "Yes" and "No" as labels to their radio button):
    var labelno = document.createElement("label"); 
    labelno.for="form2_no"; 
    labelno.innerHTML = "No"; 
    document.getElementById("form2_no").appendChild(labelno);
    var labelyes = document.createElement("label"); 
    labelyes.for="form2_yes"; 
    labelyes.innerHTML = "Yes"; 
    document.getElementById("form2_yes").appendChild(labelyes);

}      
</script>

1 个答案:

答案 0 :(得分:13)

这样的东西可用于创建按钮和标签。

<div id="radio_home"></div>

<script>

  var radio_home = document.getElementById("radio_home");

  function makeRadioButton(name, value, text) {

    var label = document.createElement("label");
    var radio = document.createElement("input");
    radio.type = "radio";
    radio.name = name;
    radio.value = value;

    label.appendChild(radio);

    label.appendChild(document.createTextNode(text));
    return label;
  }

  var yes_button = makeRadioButton("yesbutton", "yes", "Oh yea! do it!");
  radio_home.appendChild(yes_button);
</script>