I am doing a project (school) and need help with JavaScript programming. The code can be seen here: https://jsfiddle.net/zvov1jpr/3/
HTML:
<script src="java.js"></script>
<div id="formular">
<div id="formulartekst">
<form>
<h2 class="formskrift">Order Hot Food</h2>
<p class="kroner">$39 / $29 when 3 or more checked</p>
<input name="product" value="39" type="checkbox" id="p1" onclick="totalIt()" /> Monday
<br>
<input name="product" value="39" type="checkbox" id="p2" onclick="totalIt()" /> Tuesday
<br>
<input name="product" value="39" type="checkbox" id="p3" onclick="totalIt()" /> Wednesday
<br>
<input name="product" value="39" type="checkbox" id="p4" onclick="totalIt()" /> Thursday
<br>
<input name="product" value="39" type="checkbox" id="p5" onclick="totalIt()" /> Friday
<label>
<br> Total
<input value="$0.00" readonly type="text" id="total" />
</label>
<input type="submit" value="Order">
</form>
</div>
</div>
JavaScript:
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "$" + total.toFixed(2);
}
When I check boxes it automatically adds up the price (for some reason it doesn't on JSFiddle but it works fine on my website). However, I need it so when I have 3 or more boxes checked, it has to change the price to $29 pr. Check instead of $39.
There was a small JSFiddle issue that I have already commented about.
Apart from that you can use querySelectors to reduce code.
JSFiddle
function totalIt() {
var input = document.querySelectorAll("input[name='product']:checked")
document.getElementById("total").value = "$" +
(input.length * (input.length > 2 ? 29 : 39))
}
<script src="java.js"></script>
<div id="formular">
<div id="formulartekst">
<form>
<h2 class="formskrift">Order Hot Food</h2>
<p class="kroner">$39 / $29 when 3 or more checked</p>
<input name="product" value="39" type="checkbox" id="p1" onclick="totalIt()" />Monday
<br>
<input name="product" value="39" type="checkbox" id="p2" onclick="totalIt()" />Tuesday
<br>
<input name="product" value="39" type="checkbox" id="p3" onclick="totalIt()" />Wednesday
<br>
<input name="product" value="39" type="checkbox" id="p4" onclick="totalIt()" />Thursday
<br>
<input name="product" value="39" type="checkbox" id="p5" onclick="totalIt()" />Friday
<label>
<br>Total
<input value="$0.00" readonly type="text" id="total" />
</label>
<input type="submit" value="Order">
</form>
</div>
</div>
Change your function to:
function totalIt(){
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total+= 1;
}
}
if(total>=3){
document.getElementById("total").value = "$" + (total*29).toFixed(2);
}
else{
document.getElementById("total").value = "$" + (total*39).toFixed(2);
}
Related
Let's assume I have an array of check boxes (not necessarily as a part of a form). In my case 2 rows with 16 check boxes per row.
Each has his unique ID, name and value.
I need An action button to send to a form a concatenated string of selected check boxes and also to another input the number of selected boxes (count of checked) This inputs are part of a form containing and other inputs.
This is my basic functionality diagram:
diagram of1
My question for you is how to achieve this in a stable and safe manner. JS, Jquery, other methods?
Thank you,
Here is my html/Jsquery work:
//Select interval with Shift
$(document).ready(function() {
var $chkboxes = $('.chkbox');
var lastChecked = null;
$chkboxes.click(function(e) {
if (!lastChecked) {
lastChecked = this;
return;
}
if (e.shiftKey) {
var start = $chkboxes.index(this);
var end = $chkboxes.index(lastChecked);
$chkboxes.slice(Math.min(start, end), Math.max(start, end) + 1).prop('checked', lastChecked.checked);
}
lastChecked = this;
});
});
//count checked
var form = document.getElementById('chart');
var checkBoxes = $(form).children('.chkbox');
var count = 0;
var divBoxesChecked = document.getElementById('boxesChecked');
divBoxesChecked.innerHTML = 0;
$(checkBoxes).on('change', function() {
$.each(checkBoxes, function(i) {
if (checkBoxes[i].checked) {
count++;
}
});
var qty = count;
var seld = $('.chkbox:checked').map(function() {
return this.value;
})
.get()
.join(",");
$("#transfercape").on('click', function() {
var pid = 125;
var price = 4;
$('#productprice').val(price);
$('#productID').val(pid);
$('#elements').val(qty);
$('#selectionprice').val(price * qty);
$('#teeth').val(seld);
});
$("#transferbonturi").on('click', function() {
var pid = 155;
var price = 40;
$('#productprice').val(price);
$('#productID').val(pid);
$('#elements').val(qty);
$('#selectionprice').val(price * qty);
$('#teeth').val(seld);
});
console.log(count);
//console.log($('input[class=chkbox]:checked').val(","));
divBoxesChecked.innerHTML = count + " elemente selectate ";
console.log(seld);
count = 0;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="chart">
<h1>Chart</h1>
<input type="checkbox" class="chkbox" id="maxila18" name="maxila18" value="18">
<label for="maxila1"> 18</label>
<input type="checkbox" class="chkbox" id="maxila17" name="maxila17" value="17">
<label for="maxila17">17</label>
<input type="checkbox" class="chkbox" id="maxila16" name="maxila16" value="16">
<label for="maxila16">16</label>
<input type="checkbox" class="chkbox" id="maxila15" name="maxila15" value="15">
<label for="maxila15"> 15</label>
<input type="checkbox" class="chkbox" id="maxila14" name="maxila14" value="14">
<label for="maxila14"> 14</label>
<input type="checkbox" class="chkbox" id="maxila13" name="maxila13" value="13">
<label for="maxila13"> 13</label>
<input type="checkbox" class="chkbox" id="maxila12" name="maxila12" value="12">
<label for="maxila12"> 12</label>
<input type="checkbox" class="chkbox" id="maxila11" name="maxila11" value="11">
<label for="maxila11"> 11</label>
<input type="checkbox" class="chkbox" id="maxila21" name="maxila21" value="21">
<label for="maxila21"> 21</label>
<input type="checkbox" class="chkbox" id="maxila22" name="maxila22" value="22">
<label for="maxila22"> 22</label>
<input type="checkbox" class="chkbox" id="maxila23" name="maxila23" value="23">
<label for="maxila23"> 23</label>
<input type="checkbox" class="chkbox" id="maxila24" name="maxila24" value="24">
<label for="maxila24"> 24</label>
<input type="checkbox" class="chkbox" id="maxila25" name="maxila25" value="25">
<label for="maxila25"> 25</label>
<input type="checkbox" class="chkbox" id="maxila26" name="maxila26" value="26">
<label for="maxila26"> 26</label>
<input type="checkbox" class="chkbox" id="maxila27" name="maxila27" value="27">
<label for="maxila27"> 27</label>
<input type="checkbox" class="chkbox" id="maxila28" name="maxila28" value="28">
<label for="maxila28"> 28</label>
<br>
<input type="checkbox" class="chkbox" id="mandible38" name="mandible38" value="38">
<label for="mandible3"> 38</label>
<input type="checkbox" class="chkbox" id="mandible37" name="mandible37" value="37">
<label for="mandible37">37</label>
<input type="checkbox" class="chkbox" id="mandible36" name="mandible36" value="36">
<label for="mandible36">36</label>
<input type="checkbox" class="chkbox" id="mandible35" name="mandible35" value="35">
<label for="mandible35"> 35</label>
<input type="checkbox" class="chkbox" id="mandible34" name="mandible34" value="34">
<label for="mandible34"> 34</label>
<input type="checkbox" class="chkbox" id="mandible33" name="mandible33" value="33">
<label for="mandible33"> 33</label>
<input type="checkbox" class="chkbox" id="mandible32" name="mandible32" value="32">
<label for="mandible32"> 32</label>
<input type="checkbox" class="chkbox" id="mandible31" name="mandible31" value="31">
<label for="mandible31"> 31</label>
<input type="checkbox" class="chkbox" id="mandible41" name="mandible41" value="41">
<label for="mandible43"> 41</label>
<input type="checkbox" class="chkbox" id="mandible42" name="mandible42" value="42">
<label for="mandible42"> 42</label>
<input type="checkbox" class="chkbox" id="mandible43" name="mandible43" value="43">
<label for="mandible43"> 43</label>
<input type="checkbox" class="chkbox" id="mandible44" name="mandible44" value="44">
<label for="mandible44"> 44</label>
<input type="checkbox" class="chkbox" id="mandible45" name="mandible45" value="45">
<label for="mandible45"> 45</label>
<input type="checkbox" class="chkbox" id="mandible46" name="mandible46" value="46">
<label for="mandible46"> 46</label>
<input type="checkbox" class="chkbox" id="mandible47" name="mandible47" value="47">
<label for="mandible47"> 47</label>
<input type="checkbox" class="chkbox" id="mandible48" name="mandible48" value="48">
<label for="mandible48"> 48</label>
<br>
</div>
<div>
<h3> numar elemente selectate</h3>
<div id="boxesChecked"> </div>
</div>
<input type="button" value="ADD CAPE" id="transfercape">!Cape CrCo(4euro) </input>
<input type="button" value="ADD Bonturi" id="transferbonturi">!Bonturi(40euro) </input>
<div id="container1">
<form>
<input type="text" / id="elements" placeholder="elements">
<input type="text" / id="productID" placeholder="productID">
<input type="text" / id="productprice" placeholder="productprice">
<input type="text" / id="selectionprice" placeholder="selectionprice">
<input type="text" / id="teeth" name="teeth " placeholder="teeth" value="">
</form>
</div>
This solved practically main problem, still I can't figure how to replace join separator between consecutive selected boxes from comma to minus.
String returned by .map() function need to conditionally change separator for consecutively checked boxes.
Example:
Checked: 18 14 13 12 24
Now the result is: 18,14,13,12,24
but I need to be: 18,14-13-12,24
Please help!
I would like to do this quiz "Buzzfeed Style" where i choose certain answers, and based on what I've chosen I receive a certain artist to listen to. I am trying to do this right now by using an HTML form and JavaScript. I cannot get the results to show. I have included the JavaScript and HTML I am working with below.
Any help would be greatly appreciated.
var season = 0;
var activity = 0;
var meal = 0;
var vacation = 0;
var total = 0;
function displayResult() {
season = parseInt(document.querySelector('input[name = "season"]:checked').value);
activity = parseInt(document.querySelector('input[name = "activity"]:checked').value);
meal = parseInt(document.querySelector('input[name = "meal"]:checked').value);
vacation = parseInt(document.querySelector('input[name = "vacation"]:checked').value);
total = season + activity + meal + vacation;
document.getElementById("answer").innerHTML = total;
if (total < 4) {document.getElementById("answer2").innerHTML = "You got Taylor Swift."; }
else if (total >= 4 && total < 7) {document.getElementById("answer2").innerHTML = "You got Justin Bieber."; }
else if (total >= 7) {document.getElementById("answer2").innerHTML = "You got Maroon 5."; }
else {alert("Fill out all questions before submitting."); }
return false; }
window.onload = function () {document.getElementById("form1").onclick = displayResult; };
<!--Quiz-->
<div id="main">
<div id="header1">
<h1>Which <span id="solo">SOLO</span> PENGUIN RECORDS artist should you listen to?</h1>
</div>
<form id="form1" action="#">
<p>What is your favorite season?</p>
<td>
<tr>
<p class="rb">
<label>
<input type="radio" name="season" id="summer" value="0" />
<span>Summer</span>
</label>
</p>
<p class="rb">
<label>
<input type="radio" name="season" id="fall" value="1" >
<span>Fall</span>
</label>
</p>
<p class="rb">
<label>
<input type="radio" name="season" id="winter" value="2" >
<span>Winter</span>
</label>
</p>
<p class="rb">
<label>
<input type="radio" name="season" id="spring" value="3" >
<span>Spring</span>
</label>
</p>
</tr>
</td>
<p>Where would you prefer to spend your Saturday Morning?</p>
<td>
<tr>
<p class="rb">
<label>
<input type="radio" name="activity" id="gym" value="1" />
<span>The gym</span>
</label>
</p>
<p class="rb">
<label>
<input type="radio" name="activity" id="bed" value="3" />
<span>In bed</span>
</label>
</p>
<p class="rb">
<label>
<input type="radio" name="activity" id="coffee" value="2" />
<span>Coffee Shop</span>
</label>
</p>
</tr>
</td>
<p>What is your favorite meal of the day</p>
<td>
<tr>
<p class="rb">
<label>
<input type="radio" name="meal" id="bfast" value="0" />
<span>Breakfast</span>
</label>
</p>
<p class="rb">
<label>
<input type="radio" name="meal" id="brunch" value="1" />
<span>Brunch</span>
</label>
</p>
<p class="rb">
<label>
<input type="radio" name="meal" id="lunch" value="2" />
<span>Lunch</span>
</label>
</p>
<p class="rb">
<label>
<input type="radio" name="meal" id="dinner" value="3" />
<span>Dinner</span>
</label>
</p>
</tr>
</td>
<p>Where is your dream vacation destination?</p>
<td>
<tr>
<p class="rb">
<label>
<input type="radio" name="vacation" id="island" value="1" />
<span>Tropical Island</span>
</label>
</p>
<p class="rb">
<label>
<input type="radio" name="vacation" id="Mountains" value="2" />
<span>Mountainside</span>
</label>
</p>
<p class="rb">
<label>
<input type="radio" name="vacation" id="City" value="3" />
<span>Bustling City</span>
</label>
</p>
</tr>
</td>
<br/><br/>
<button class="btn waves-effect waves-light black" type="submit" name="action" id="submitForm" value="submit" onSubmit="algorithm.js">Submit</button>
</form>
<p id="answer"></p>
<p id="answer2"></p>
</div>
In your way you should take the season, activity, meal and vacation from URL parameters (?season=0&activity=1&meal=0&vacation=1&action=submit#), and not directly form radiobox, because you are using <form> and onSubmit.
If you want an asyncronously behavior and get the result directly from the radioboxes, you can remove <form> and the submit button, and use this code below:
<script type="text/javascript">
(function () {
Array.from(document.getElementsByTagName("input")).map((elem) => {
elem.addEventListener('change', () => {
season = parseInt(document.querySelector('input[name = "season"]:checked').value);
activity = parseInt(document.querySelector('input[name = "activity"]:checked').value);
meal = parseInt(document.querySelector('input[name = "meal"]:checked').value);
vacation = parseInt(document.querySelector('input[name = "vacation"]:checked').value);
total = season + activity + meal + vacation;
document.getElementById("answer").innerHTML = total;
if (total < 4) {document.getElementById("answer2").innerHTML = "You got Taylor Swift."; }
else if (total >= 4 && total < 7) {document.getElementById("answer2").innerHTML = "You got Justin Bieber."; }
else if (total >= 7) {document.getElementById("answer2").innerHTML = "You got Maroon 5."; }
else {alert("Fill out all questions before submitting."); }
return false;
});
});
})();
I have found a code to display the final price based on some selections from a form imputs (checkbox) affecting the final price. I want also it to affect an external div with text on it. Is a huge fixed element I've created displaying "Final Cost" and I also want this to render the final price by changing the getElementByID and nothing happened. Could you help me to solve this?
I want also .priceText1 also to be affected:)
Actual code is
HTML
<form action="" id="theForm">
<fieldset>
<legend>
Products
</legend>
<label>
<input name="product" value="12.95" type="checkbox" id="p1" onclick="totalIt()"/>
Candy $12.95
</label>
<label>
<input name="product" value="5.99" type="checkbox" id="p2" onclick="totalIt()"/>
Burger $5.99
</label>
<label>
<input name="product" value="1.99" type="checkbox" id="p3" onclick="totalIt()"/>
Coke $1.99
</label>
<label>
Total
<input value="$0.00" readonly="readonly" type="text" id="total"/>
</label>
</fieldset>
<input value="Submit" type="submit"/>
<input value="Reset" type="reset"/>
</form>
<div class="priceWrapper">
<h3 class="priceText1">$0.00</h3>
<h3 class="priceText2">Final Cost</h3>
</div>
JS
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "$" + total.toFixed(2);
}
You could simply use innerText with querySelector to add the total price to the element .priceText1 like :
document.querySelector(".priceText1").innerText = "$" + total.toFixed(2);
Hope this helps.
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "$" + total.toFixed(2);
document.querySelector(".priceText1").innerText = "$" + total.toFixed(2);
}
<form action="" id="theForm">
<fieldset>
<legend>
Products
</legend>
<label>
<input name="product" value="12.95" type="checkbox" id="p1" onclick="totalIt()"/>
Candy $12.95
</label>
<label>
<input name="product" value="5.99" type="checkbox" id="p2" onclick="totalIt()"/>
Burger $5.99
</label>
<label>
<input name="product" value="1.99" type="checkbox" id="p3" onclick="totalIt()"/>
Coke $1.99
</label>
<label>
Total
<input value="$0.00" readonly="readonly" type="text" id="total"/>
</label>
</fieldset>
<input value="Submit" type="submit" />
<input value="Reset" type="reset" />
</form>
<div class="priceWrapper">
<h3 class="priceText1">$0.00</h3>
<h3 class="priceText2">Final Cost</h3>
</div>
I'm trying to get a drop down menu to work with a price calculation form, but the drop down menu won't add any price value to the total price. I'm pretty bad at doing these things, so maybe one of you knows how to fix this?
This is the link to the code.
HTML:
<form action="" id="theForm">
<fieldset>
<legend>
Products
</legend>
<label>
<input name="product" value="12.95" type="checkbox" id="p1" onclick="totalIt()"/>
Extra domein $12.95
</label>
<label>
<input name="product" value="5.99" type="checkbox" id="p2" onclick="totalIt()"/>
Verlengservice $5.99
</label>
<label>
<input name="product" value="1.99" type="checkbox" id="p3" onclick="totalIt()"/>
Domein support $1.99
</label>
<select name="product" id="p3" onclick="totalIt()"/>
<option value="249">Thema 'Ambachtelijk'</option>
<option value="249">Thema 'Blog - Lifestyle'</option>
<option value="199">Thema 'Bed en Brood'</option>
<option value="249">Thema 'Freelancer'</option>
</select>
<label>
Total
<input value="$0.00" readonly="readonly" type="text" id="total"/>
</label>
</fieldset>
<input value="Submit" type="submit"/>
<input value="Reset" type="reset"/>
</form>
JavaScript:
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "$" + total.toFixed(2);
}
Any ideas?
You need to get the selected value from <select>
And Change onclick to onchange
The onchange event occurs when the value of an element has been changed.
Try this:
if(input[i].tagName == 'SELECT'){
total += Number(input[i].options[input[i].selectedIndex].value);
}
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if(input[i].tagName == 'SELECT'){
total += Number(input[i].options[input[i].selectedIndex].value);
}
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "$" + total.toFixed(2);
}
<form action="" id="theForm">
<fieldset>
<legend>
Products
</legend>
<label>
<input name="product" value="12.95" type="checkbox" id="p1" onchange="totalIt()"/>
Extra domein $12.95
</label>
<label>
<input name="product" value="5.99" type="checkbox" id="p2" onchange="totalIt()"/>
Verlengservice $5.99
</label>
<label>
<input name="product" value="1.99" type="checkbox" id="p3" onchange="totalIt()"/>
Domein support $1.99
</label>
<select name="product" id="p3" onchange="totalIt()"/>
<option value="249">Thema 'Ambachtelijk'</option>
<option value="249">Thema 'Blog - Lifestyle'</option>
<option value="199">Thema 'Bed en Brood'</option>
<option value="249">Thema 'Freelancer'</option>
</select>
<label>
Total
<input value="$0.00" readonly="readonly" type="text" id="total"/>
</label>
</fieldset>
<input value="Submit" type="submit"/>
<input value="Reset" type="reset"/>
</form>
You should use onchange instead of onclick for select event. The main problem is that you aren't adding the value of select in the totalIt func. Might be a good idea to give the select a different id from your 3rd checkbox.
You need to modify your html, you are using same id like p3. Also, you need to handle onchange event. Please see the reference code:
var dropdownTotal = 0;
function dropDownTotalHandler() {
var x = document.getElementById("dropdownProducts").value;
dropdownTotal += parseFloat(x);
document.getElementById("total").value = "$" + dropdownTotal.toFixed(2);
}
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "$" + total.toFixed(2);
}
<form action="" id="theForm">
<fieldset>
<legend>
Products
</legend>
<label>
<input name="product" value="12.95" type="checkbox" id="p1" onclick="totalIt()" />
Extra domein $12.95
</label>
<label>
<input name="product" value="5.99" type="checkbox" id="p2" onclick="totalIt()" />
Verlengservice $5.99
</label>
<label>
<input name="product" value="1.99" type="checkbox" id="p3" onclick="totalIt()" />
Domein support $1.99
</label>
<select name="product" id="dropdownProducts" onchange="dropDownTotalHandler()" />
<option value="249">Thema 'Ambachtelijk'</option>
<option value="249">Thema 'Blog - Lifestyle'</option>
<option value="199">Thema 'Bed en Brood'</option>
<option value="249">Thema 'Freelancer'</option>
</select>
<label>
Total
<input value="$0.00" readonly="readonly" type="text" id="total" />
</label>
</fieldset>
<input value="Submit" type="submit" />
<input value="Reset" type="reset" />
</form>
If you want to keep the event handler same, then here is one of the way how you can do it. Hopefully, this is what you want but if not feel free to change it.
First, change the html to mention totalIt as event handler like below:
onchange="totalIt(this.value)"
Then modify the script code. Here, the addition into total is happening for one checkbox at a time:
<script>
var total = 0;
function totalIt(dropDownValue) {
if (!dropDownValue) {
total += parseFloat(event.target.value);
} else {
total += parseFloat(dropDownValue);
}
document.getElementById("total").value = "$" + total.toFixed(2);
}
</script>
See if this is what you are looking for?
HTML
<div id="catlist">
<input type="checkbox" id="cat_1" value="cat_1" price="1.5" /><label for="cat_1">cat_1</label><br/>
<input type="checkbox" id="cat_2" value="cat_2" price="2" /><label for="cat_2">cat_2</label><br/>
<input type="checkbox" id="cat_3" value="cat_3" price="3.5" /><label for="cat_3">cat_3</label><br/>
<input type="checkbox" id="cat_4" value="cat_4" price="4" /><label for="cat_4">cat_4</label><br/>
<input type="checkbox" id="cat_5" value="cat_5" price="5" /><label for="cat_5">cat_5</label><br/>
<input type="checkbox" id="cat_6" value="cat_6" price="6.5" /><label for="cat_6">cat_6</label><br/>
<input type="checkbox" id="cat_7" value="cat_7" price="7" /><label for="cat_7">cat_7</label><br/>
<input type="checkbox" id="cat_8" value="cat_8" price="8" /><label for="cat_8">cat_8</label><br/>
<input type="checkbox" id="cat_9" value="cat_9" price="9.5" /><label for="cat_9">cat_9</label>
</div>
<input type="text" id="total" value="0" />
Javascript
function calcAndShowTotal(){
var total = 0;
$('#catlist :checkbox[checked]').each(function(){
total =+ parseFloat($(this).attr('price')) || 0;
});
$('#total').val(total);
}
$('#pricelist :checkbox').click(function(){
calcAndShowTotal();
});
calcAndShowTotal();
I am getting particular value. WHY? I tried sum of total, i tried jquery but no success..
Use $('#catlist :checkbox:checked') selector to select checked check-boxes
[] is used as attribute selector and it could be used as '[type="checkbox"]' but it will not filter checked check-boxes
+ operator is not needed before parseFloat, it has to be total =+
Instead of calling handler, just invoke change handler using .change()
function calcAndShowTotal() {
var total = 0;
$('#catlist :checkbox:checked').each(function() {
total += parseFloat($(this).attr('price')) || 0;
});
$('#total').val(total);
}
$('#catlist :checkbox').change(calcAndShowTotal).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="catlist">
<input type="checkbox" id="cat_1" value="cat_1" price="1.5" />
<label for="cat_1">cat_1</label>
<br/>
<input type="checkbox" id="cat_2" value="cat_2" price="2" />
<label for="cat_2">cat_2</label>
<br/>
<input type="checkbox" id="cat_3" value="cat_3" price="3.5" />
<label for="cat_3">cat_3</label>
<br/>
<input type="checkbox" id="cat_4" value="cat_4" price="4" />
<label for="cat_4">cat_4</label>
<br/>
<input type="checkbox" id="cat_5" value="cat_5" price="5" />
<label for="cat_5">cat_5</label>
<br/>
<input type="checkbox" id="cat_6" value="cat_6" price="6.5" />
<label for="cat_6">cat_6</label>
<br/>
<input type="checkbox" id="cat_7" value="cat_7" price="7" />
<label for="cat_7">cat_7</label>
<br/>
<input type="checkbox" id="cat_8" value="cat_8" price="8" />
<label for="cat_8">cat_8</label>
<br/>
<input type="checkbox" id="cat_9" value="cat_9" price="9.5" />
<label for="cat_9">cat_9</label>
</div>
<input type="text" id="total" value="0" />
Using Array#reduce
function calcAndShowTotal() {
var total = [].reduce.call($('#catlist :checkbox:checked'), function(a, b) {
return a + +$(b).attr('price') || 0;
}, 0);
$('#total').val(total);
}
$('#catlist :checkbox').change(calcAndShowTotal).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="catlist">
<input type="checkbox" id="cat_1" value="cat_1" price="1.5" />
<label for="cat_1">cat_1</label>
<br/>
<input type="checkbox" id="cat_2" value="cat_2" price="2" />
<label for="cat_2">cat_2</label>
<br/>
<input type="checkbox" id="cat_3" value="cat_3" price="3.5" />
<label for="cat_3">cat_3</label>
<br/>
<input type="checkbox" id="cat_4" value="cat_4" price="4" />
<label for="cat_4">cat_4</label>
<br/>
<input type="checkbox" id="cat_5" value="cat_5" price="5" />
<label for="cat_5">cat_5</label>
<br/>
<input type="checkbox" id="cat_6" value="cat_6" price="6.5" />
<label for="cat_6">cat_6</label>
<br/>
<input type="checkbox" id="cat_7" value="cat_7" price="7" />
<label for="cat_7">cat_7</label>
<br/>
<input type="checkbox" id="cat_8" value="cat_8" price="8" />
<label for="cat_8">cat_8</label>
<br/>
<input type="checkbox" id="cat_9" value="cat_9" price="9.5" />
<label for="cat_9">cat_9</label>
</div>
<input type="text" id="total" value="0" />
Instead of looping you can use change which will respond to and change event on the checkbox. Also you need add or subtract value like this += for addition on -= for subtraction
var _total = 0;
$('input[type="checkbox"]').change(function() {
if($(this).is(':checked')){
_total += parseFloat($(this).attr('price')) || 0;
}
else{
_total -= parseFloat($(this).attr('price')) || 0;
}
$('#total').val(_total);
})
JSFIDDLE
$('input:checkbox').change(function(){
var totalprice=0;
$('input:checkbox:checked').each(function(){
totalprice+= parseFloat($(this).attr('price'));
});
$('#total').val(totalprice)
});