提交后,通过if语句测试输入无线电值

时间:2018-01-01 04:56:23

标签: javascript jquery html

代码:

function checkInput() {
  var input1 = document.getElementById("on").value;
  var input = document.getElementById("off").value;

  if (input1 === "on") {
    document.getElementById('reponse').innerHTML = "LED EST ON";
    return false;
  }
  
  if (input === "off") {
    document.getElementById('reponse').innerHTML = "LED EST off";
    return false;
  }
}
<form action="url" method="POST">
  Allumer la LED D7 <br>
  <br>
  <input type="radio" name="arg" value="on" id="on">On.
  <br>
  <input type="radio" name="arg" value="off" id="off">Off.
  <br>
  <br>
  <input type="submit" value="OK" onclick="checkInput()">
  <br>
</form>
<p id="reponse"> </p>

我想如果我选择On并提交,我会收到一条消息“LED EST ON”;

如果我选择关闭并提交,我会收到“LED EST Off”

1 个答案:

答案 0 :(得分:1)

您可以采用更简单的方式执行此操作,如下所示:

&#13;
&#13;
function checkInput(){
  var input = document.querySelectorAll("input[type=radio]:checked");
  if (input[0].getAttribute('value') == 'on') {
  document.getElementById('reponse').innerHTML  = "LED EST ON";
    return false;
  }  
  else{
    document.getElementById('reponse').innerHTML  = "LED EST off";
    return false;
  }
}
&#13;
<input type ="radio" name="arg" value="on" id="on" >On.
<br>
<input type="radio" name="arg" value="off" id="off" >Off.
<br>
<br>
<input type="submit" value="OK" onclick="checkInput()" >
<br>
<p id="reponse" > </p>
&#13;
&#13;
&#13;