使用javascript评估表单输入单选按钮

时间:2015-12-27 12:07:34

标签: javascript forms radio-button

我正在设置一个h2元素,以显示通过表单中的单选按钮回答的问题的分数。当答案正确但h1文本更改为毫秒然后返回显示零时,将弹出祝贺消息。

var h2 = document.querySelector("h2");
var correctAnswers = 0;
h2.textContent = correctAnswers;

function getAnswer(){
  var radio = document.querySelector("form");
  if (radio[0].checked === true) {
    correctAnswers++;
    alert("Congrats! That answer is correct!");

  }
  h2.textContent = correctAnswers;
}

var btn = document.getElementById('btn');

btn.addEventListener("click", getAnswer);

HTML看起来像这样

<body>
<h1></h1>
<form>

    <p>John Resig invented which javascript library?</p>
<input type="radio" name="library" value="jQuery">jQuery
<input type="radio" name="library" value="Lodash">Lodash
<input type="radio" name="library" value="Underscore">Underscore 
<input id="btn" type="submit"> </form>

<script src="quiz.js"></script> 
</body>

2 个答案:

答案 0 :(得分:1)

Your page is reloading on submit to avoid that you can use as below
 form onsubmit="return false;"
<body>
<h2></h2>
<form onsubmit="return false;">

    <p>John Resig invented which javascript library?</p>
<input type="radio" name="library" value="jQuery">jQuery
<input type="radio" name="library" value="Lodash">Lodash
<input type="radio" name="library" value="Underscore">Underscore 
<input id="btn" type="submit"> </form>

<script>
var h2 = document.querySelector("h2");
var correctAnswers = 0;
h2.textContent = correctAnswers;

function getAnswer(){
  var radio = document.querySelector("form");
  if (radio[0].checked === true) {
    correctAnswers++;
    alert("Congrats! That answer is correct!");

  }
  h2.textContent = correctAnswers;
}

var btn = document.getElementById('btn');

btn.addEventListener("click", getAnswer);
</script> 
</body>

答案 1 :(得分:0)

当我加载代码并检查浏览器控制台时,我看到了以下消息:

  

TypeError:h2为null

     

h2.textContent = correctAnswers;

这是因为这一行指定了'h2':

$last = '';
$generator = mySortFunction($records);
foreach($generator as $result) {
  if(substr($result, 0, 1) != $last && $last != '') {
    echo "<br>"; // put an extra line between each letter
  }
  echo $result
}

您可以在html中将var h2 = document.querySelector("h2"); 更改为<h1></h1>,或添加<h2></h2>

如果我例如添加<h2></h2>,您确实会看到将1更改为零。 这是因为当您单击按钮并重新加载页面时,表单会执行GET请求。

如果您不希望在点击按钮后重新加载页面,您可以将其添加到表单标记中:

<h2></h2>

段:

<form onsubmit="return false;">
var h2 = document.querySelector("h2");
var correctAnswers = 0;
h2.textContent = correctAnswers;

function getAnswer(){
  var radio = document.querySelector("form");
  if (radio[0].checked === true) {
    correctAnswers++;
    alert("Congrats! That answer is correct!");

  }
  h2.textContent = correctAnswers;
}

var btn = document.getElementById('btn');

btn.addEventListener("click", getAnswer);