Javascript DOM HTML Input Checkbox get value for checked checkbox

Introduction

Several checkboxes in a form:

View in separate window

<!DOCTYPE html>
<html>
<body>
<p>How would you like your coffee?</p>

<form action="/server.php">
<input type="checkbox" name="coffee" value="cream">With cream<br>
<input type="checkbox" name="coffee" value="sugar">With sugar<br>
<br>
<input type="button" onclick="myFunction()" value="Send order">
<br><br>
<input type="text" id="order" size="50">
<input type="submit" value="Submit">
</form>//w w w  .j a va 2s  . co  m

<script>
function myFunction() {
  var coffee = document.forms[0];
  var txt = "";
  var i;
  for (i = 0; i < coffee.length; i++) {
    if (coffee[i].checked) {
      txt = txt + coffee[i].value + " ";
    }
  }
  document.getElementById("order").value = "You ordered a coffee with: " + txt;
}
</script>

</body>
</html>



PreviousNext

Related