简体   繁体   中英

Get values of all checked boxes in input type checkbox in javascript

I have made a function to get the values of checked boxes and placing all values in an input field. But i am getting problem in the result in which i want to remove the last comma. I have tried slice but could not succeded. Please help me out.

<!DOCTYPE html>
<html>
<body>

<p>How would you like your coffee?</p>

<form name="myform" action="/action_page.php">
<input type="checkbox" name="coffee" value="100">With cream<br>
<input type="checkbox" name="coffee" value="150">With sugar<br>
<input type="checkbox" name="coffee" value="200">With milk<br>
<input type="checkbox" name="coffee" value="250">With tea<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>

<script>
function myFunction() {
  var coffee = document.forms["myform"];
  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>

Use an array, push the values inside the for loop, then use join()

var txt = [];
var i;
for (i = 0; i < coffee.length; i++) {
  if (coffee[i].checked) {
    txt.push(coffee[i].value);
  }
}
document.getElementById("order").value = "You ordered a coffee with: " + txt.join(', ');

As a side note, with querySelectorAll() you could select only the checked chekboxes, without using a condition inside the loop:

var coffee = [...document.querySelectorAll('[name="myform"] input:checked')];
var i, txt = [];

for (i = 0; i < coffee.length; i++) {
    txt.push(coffee[i].value);
}
document.getElementById("order").value = "You ordered a coffee with: " + txt.join(', ');

If you know for sure that txt will always have a comma at the end and you want to use slice you could run txt = txt.slice(0,-2) . The -2 is because you have ", " which is two characters. but the array answer is a better approach.

function myFunction() {
  var coffee = document.forms["myform"];
  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.substring(0, txt.length - 1);

}

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