简体   繁体   中英

How to access checkbox form values after hitting the submit button with Javascript?

Suppose you have this:

<!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>

You want the Javascript to make the value of the checked box appear on screen once submit is clicked, but it keeps printing 'undefined' so obviously it's not accessing the form correctly. What's the problem?

<!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>

see here https://jsfiddle.net/mbkj6zv4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM