为每个单选按钮分配功能

时间:2016-05-20 21:11:55

标签: jquery button radio

我知道这可能很傻,但我是新手。 这里的东西是这样的: 我有两个单选按钮,我想根据你选择的内容获取消息,但是我收到了同样的消息,我不知道我做错了什么:

<form method="post" action="demoform.asp">
      <fieldset data-role="controlgroup">
      <legend>choose number</legend>
        <label for="one">number one</label>
        <input type="radio" id="number" name="1" value="1">
        <label for="second">number two</label>
        <input type="radio"  id="number" name="2" value="2">
      </fieldset>
       <p id="demo"></p>
        <input type="button" id="demo" onclick="myfunction()" >Click me</button>
    </form>

和脚本:

function myfunction() {
    var place = document.getElementById("number").value;
    var text;


    if (place === "1") {
        text = "Spot Good job!";


    } else if (place === "2" ) {
        text = " close enough.";
            } 
document.getElementById("demo").innerHTML = text;
}

2 个答案:

答案 0 :(得分:0)

如果您希望单选按钮作为真正的单选按钮工作,则它们应具有相同的name属性。您也不能拥有具有相同id属性的多个元素。最后,您的HTML在按钮上有语法错误。

function myfunction() {
    var place = document.querySelector('input[name="number"]:checked');
    var text;

    if (!place) {
        text = "Select a radio option";
    } else if (place.value === "1") {
        text = "Spot Good job!";
    } else if (place.value === "2" ) {
        text = " close enough.";
    } 
  
    document.getElementById("demo").innerHTML = text;
}
<form method="post" action="demoform.asp">
      <fieldset data-role="controlgroup">
        <legend>choose number</legend>
        <label for="number_1">number one</label>
        <input type="radio" id="number_1" name="number" value="1">
        <label for="number_2">number two</label>
        <input type="radio"  id="number_2" name="number" value="2">
      </fieldset>
      
      <p id="demo"></p>

      <button type="button" id="demo" onclick="myfunction()" >Click me</button>
</form>

答案 1 :(得分:0)

您的单选按钮必须具有相同的名称,但必须具有唯一的ID。 你可以使用

<label for="one">number one</label>
<input type="radio" id="n1" name="number" value="1">
<label for="second">number two</label>
<input type="radio"  id="n2" name="number" value="2">
<input type="button" id="demo" onclick="myfunction()" >Click me</button>

使用javascript:

var text;
if(document.getElementById("n1").checked)
    text = "Spot Good job!";
if(document.getElementById("n2").checked)
    text = " close enough.";
document.getElementById("demo").innerHTML = text;