从多组单选按钮捕获值

时间:2014-04-15 17:42:10

标签: javascript forms

我认为这个很简单,但我真的需要一些帮助。感谢任何帮助的人!!

我试图从两组单选按钮中捕获输入。第一组起作用,但第二组不起作用。

这是我的代码:

HTML

<p>Please select one from each group.</p>

<form action="#">

    <fieldset>
      <input type="radio" name="type" value="classic">classic type<br>
      <input type="radio" name="type" value="modern">modern type<br>
      <br>
      <input type="button" onclick="typeface()" value="Review type selection">
      <br><br>
      <input type="text" id="type" size="50">
    </fieldset>

    <fieldset>
      <input type="radio" name="layout" value="layout1">layout1<br>
      <input type="radio" name="layout" value="layout2">layout2<br>
      <br>
      <input type="button" onclick="layout()" value="Review layout selection">
      <br><br>
      <input type="text" id="layout" size="50">   
    </fieldset>

    <input type="submit" value="Submit">

</form>

JS(</body>之前)

function typeface(){
  var type = document.forms[0].type;
  var txt = "";
  var i;
  for (i=0;i<type.length;i++){
    if (type[i].checked){
      txt = txt + type[i].value + " ";
    }
  }
  document.getElementById("type").value = "You selected: " + txt;
}

function layout(){
  var layout = document.forms[0].layout;
  var txt = "";
  var i;
  for (i=0;i<layout.length;i++){
    if (layout[i].checked){
      txt = txt + layout[i].value + " ";
    }
  }
  document.getElementById("layout").value = "You selected: " + txt;
}

2 个答案:

答案 0 :(得分:1)

如果不是通过确认他们的无线电选择来惹恼用户,而是采取以下措施:

<强> DEMO

HTML

<form id="myForm" action="#">

  <fieldset>
    <input type="radio" name="type" value="classic">classic type<br>
    <input type="radio" name="type" value="modern">modern type<br>
    <br>
    <input type="text" id="type" size="50">
  </fieldset>

  <fieldset>
    <input type="radio" name="layout" value="layout1">layout1<br>
    <input type="radio" name="layout" value="layout2">layout2<br>
    <br>
    <input type="text" id="layout" size="50">
  </fieldset>
  <input type="submit" value="Submit">

</form>

JS:

function getId(id){ return document.getElementById(id); }
function writeVal(){
  getId(this.name).value = "You selected: "+this.value;
}

var radio = getId('myForm').querySelectorAll('input[type=radio]');
for(var i=0; i<radio.length; i++) radio[i].onchange = writeVal;


以上内容将立即在广播change中生效,并在text字段中显示所选文字值。

答案 1 :(得分:0)

我不确切知道为什么,但如果你将布局功能名称更改为其他功能 fiddle

<input type="button" onclick="layout2()" value="Review layout selection">

function layout2()
{
...
}