Reputation: 107
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>
Upvotes: 1
Views: 77
Reputation: 123397
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(', ');
Upvotes: 1
Reputation: 443
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);
}
Upvotes: 0
Reputation:
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.
Upvotes: 0