1

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>
2
  • var newStr = txt.substring(0, txt.length - 1); Commented Jan 22, 2020 at 10:23
  • Consider using map instead of the for loop, and then use join. Commented Jan 22, 2020 at 10:27

3 Answers 3

1

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(', ');
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0
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);

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.