I am preparing a cart where the pricing derives from the number of items selected in menu. I am using javascript to calculate price on the same page.
function myFunction() {
var coffee = document.forms[0];
var txt = 0;
var i;
for (i = 0; i < coffee.length; i++) {
if (coffee[i].checked) {
txt = txt++;
}
}
document.getElementById("order").value = txt;
}
<label> Select the project category you will like to float </label>
<div class="form-group">
<input type="checkbox" name="coffee" value="1">Web Development
<input type="checkbox" name="coffee" value="1">App Development
<input type="checkbox" name="coffee" value="1">SEO Ninja
<input type="checkbox" name="coffee" value="1">The Social media geek
<input type="checkbox" name="coffee" value="1">Design Wizard
<input type="checkbox" name="coffee" value="1">The contest of Content
<input type="checkbox" name="coffee" value="1">Marketing Marathon
<input type="checkbox" name="coffee" value="1">Recruitment Hackathon
</div>
<input type="button" onclick="myFunction()" value="Add to cart">
<input type="text" id="order" size="50">
<div class="row">
<div class="form-group">
<ul class="actions">
<input type="submit" name="submit3" value="Register">
</ul>
</div>
</div>
</form>
Can somebody help me return an integer value (= no. of items checked) with txt.
3
Answers
When you use
txt = txt++;
you are replacing the next value with the old value. You need to use justtxt++
. Also, I think it’s better if you give an id to the form to make sure that you are targetting the right form because ids are/must unique. See the working snippets below please:As you can see I’ve also added a opening tag for the
form
element.You can run the working snippet from here or you can take a look JSFIDDLE to test it if you want.
An alternative without the old
onclick
would be too useaddEventListener
for the click like this:I’ve seen you tagged this as
jQuery
too. Here’s an alternative using$(":checkbox:checked").length
:First of all you need to replace
txt = txt++
with justtxt++
ortxt = txt + 1
I also recommend you to use
document.getElementsByName('coffee');
Beacuse this guarantees that in the future if you add another input for another purpose, you won’t need to change this function.
You do not need a loop just to count number of checkboxes checked.
You can look into
querySelectorAll
and get only selected checkboxes. Now you just have to check for.length
and you havetxt
value.Note: I have added
id
attribute toform
tag to uniquely get checkboxes.Sample Code