使用Javascript点击提交按钮后如何访问复选框表单值?

时间:2017-05-29 14:40:02

标签: javascript html

假设你有这个:

<!DOCTYPE html>
<html>
<body>

<form id="clicked">

  <input type="checkbox" value="yes">yes<br>

  <input type="checkbox" value="no">no<br>

  <input type="button" onclick="Display()" type="submit" value="Submit">

</form>

<p id="change"></p>

<script>

function Display() {

    var clicked = document.getElementById("clicked").value;
    document.getElementById("change").innerHTML = clicked;
} 

</script>

</body>
</html>

您希望Javascript在点击提交后使屏幕上显示复选框的值,但它会保持打印“未定义”。很明显,它没有正确访问表单。问题是什么?

1 个答案:

答案 0 :(得分:2)

<!DOCTYPE html>
<html>
<body>

<form id="clicked">

  <input type="checkbox" id="cb1" value="yes">yes<br>

  <input type="checkbox" id="cb2" value="no">no<br>

  <input type="button" onclick="Display()" type="submit" value="Submit">

</form>

<p id="change"></p>

<script>

function Display() {

    var clicked = document.getElementById("cb1").checked;
    var clicked2 = document.getElementById("cb2").checked;
    document.getElementById("change").innerHTML = " yes : " +clicked;
    document.getElementById("change").innerHTML += "<br/> no : " + clicked2;
} 

</script>

</body>
</html>

https://jsfiddle.net/mbkj6zv4/