Sum Checked CheckBoxes Values - javascript

I'm using play framework and jquery mobile and trying to sum custom tag values of checked checkboxes but i couldn't manage this. Here is some code;
<form action="#{Waiter.payAServing()}" method="POST">
<div class="boxes">
#{list items:servs, as:'serving'}
<fieldset data-role="fieldcontain">
<div class="ui-block-a">
<input onclick="MySum()" type="checkbox" name="item" id="checkbox-${serving_index}" value="${serving.id}" to="${serving.item.price*serving.amount}" />
<label for="checkbox-${serving_index}">${serving.item.title} </label>
</div>
<div class="ui-block-b"><h2><center> ${serving.item.price*serving.amount} TL </center></h2></div>
<div class="ui-block-c"><h2> ${serving.amount} </h2></div>
</fieldset>
#{/list}
</div>
<input type="hidden" name="rid" id="rid" value="${rID}" /><br />
<input type="submit" value="Pay!" />
</form>
<div class="result"></div>
<script type="text/javascript" charset="${_reponse_encoding}">
function MySum() {
alert(0);
var selectedCustomValue = document.getElementById("checkbox-1").getAttribute("to");
var sum = 0;
alert(selectedCustomValue);
}
</script>
How can i sum to values of checked check boxes with jquery or pure javascript?

Try this:
jQuery version:
function MySum(){
var totalSum = 0;
$("input:checked[name='item']").each(function(index, el){
totalSum += parseFloat(el.value);
});
return totalSum;
}
Also to bind the click handler to checkboxes use this instead on the inline style:
$(function(){
$("[name='item']").click(MySum);
});
To get the sum of to attribute, try this:
function MySum(){
var totalSum = 0;
$("input:checked[name='item']").each(function(index, el){
totalSum += parseFloat($(el).attr("to"));
});
return totalSum;
}
A better approach would be to use data-* attributes in your markup like:
<input type="checkbox"
name="item"
id="checkbox-${serving_index}"
value="${serving.id}"
data-to="${serving.item.price*serving.amount}" />
and the MySum function would be:
function MySum(){
var totalSum = 0;
$("input:checked[name='item']").each(function(a, b){
totalSum += parseFloat($(b).data("to"));
});
return totalSum;
}

Related

When checkbox is clicked, add its value to textbox value

I'm looking to update a textbox value when a checkbox is selected, however when a checkbox is selected I get 'NaN'.
Can anyone see where I've gone wrong?
jQuery(document).ready(function($) {
var sum = 0;
$('input[type=checkbox]').click(function() {
sum = 0;
$('input[type=checkbox]:checked').each(function() {
var val = parseInt($(this).next().val());
sum += val;
});
$('#sum').val(sum);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="campaignstrategy">
<h1>Campaign Strategy</h1>
<input type="checkbox" name="awareness" value="0.01">Awareness<br>
<input type="checkbox" name="directresponse" value="0.01">Direct Response<br>
</div>
<div class="targeting">
<h1>Targeting</h1>
<ul>
<li>
<input type="checkbox" name="geographic" value="0.07" id="geographic_checkbox" onclick="GeographicFunction()">Geographic<br>
<p id="geographic_text" style="display:none">+£0.08 CPC</p>
<ul>
<li><input type="checkbox" name="regions,cities&towns" value="0.08" id="regions,cities&towns_checkbox" onclick="RegionsFunction()">Regions, Cities & Towns<br></li>
<p id="regions,cities&towns_text" style="display:none">+£0.08 CPC</p>
<li><input type="checkbox" name="ringfencing" value="0.09" id="ringfencing_checkbox" onclick="RingfencingFunction()">Ring-Fencing<br></li>
<p id="ringfencing_text" style="display:none">+£0.08 CPC</p>
</ul>
</li>
</ul>
<input id="sum" type="text" />
Why we are using "next()" and "each" together. Also parsing int and passing 0.01 value will always hydrates to 0. Try removing "next()" and parseFloat instead of parseInt
jQuery(document).ready(function($) {
var sum = 0;
$('input[type=checkbox]').click(function() {
sum = 0;
$('input[type=checkbox]:checked').each(function() {
debugger;
var val = parseFloat($(this).val());
sum += val;
});
$('#sum').val(sum);
});
});
This is how I'd do it with Vanilla Javascript:
const checkBox = document.querySelector("#checkbox")
const textBox = document.querySelector("#textbox")
checkBox.addEventListener("change", () => {
textBox.value = checkBox.checked ? textBox.value = parseFloat(textBox.value) + parseFloat(checkBox.value) : textBox.value = 0
})
<input type="text" id="textbox" value="0">
<input type="checkbox" id="checkbox" for="textbox" value="0.08">
Edit: Updated it after #mplungjan 's comment and your question.
The parseFloat() function parses an argument (converting it to a string first if needed) and returns a floating-point number.
The toFixed() method formats a number using fixed-point notation.
Learn more about toFixed()
Learn more about parseFloat()
jQuery(document).ready(function($) {
var sum = 0;
$('input[type=checkbox]').click(function() {
sum = 0;
$('input[type=checkbox]:checked').each(function(){
sum += parseFloat(this.value);
});
$('#sum').val(sum.toFixed(2));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="campaignstrategy">
<h1>Campaign Strategy</h1>
<input type="checkbox" name="awareness" value="0.01">Awareness<br>
<input type="checkbox" name="directresponse" value="0.01">Direct Response<br>
</div>
<input id="sum" type="text" />
It took a while to understand what you meant. You just want to sum all checked checkbox values?
$(() =>
$('input[type=checkbox]').on("click", () =>
$('#sum').val(
$('input[type=checkbox]:checked') // checked boxes
.map((i,fld) => +fld.value).get() // array of values
.reduce((a,b) => a+b) // summed
.toFixed(2) // rounded
)
)
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="campaignstrategy">
<h1>Campaign Strategy</h1>
<input type="checkbox" name="awareness" value="0.01">Awareness<br>
<input type="checkbox" name="directresponse" value="0.01">Direct Response<br>
</div>
<div class="targeting">
<h1>Targeting</h1>
<ul>
<li>
<input type="checkbox" name="geographic" value="0.07" id="geographic_checkbox" ">Geographic<br>
<p id="geographic_text" style="display:none">+£0.08 CPC</p>
<ul>
<li><input type="checkbox" name="regions,cities&towns" value="0.08" id="regions,cities&towns_checkbox" ">Regions, Cities & Towns<br></li>
<p id="regions,cities&towns_text" style="display:none">+£0.08 CPC</p>
<li><input type="checkbox" name="ringfencing" value="0.09" id="ringfencing_checkbox" ">Ring-Fencing<br></li>
<p id="ringfencing_text" style="display:none">+£0.08 CPC</p>
</ul>
</li>
</ul>
<input id="sum" type="text" />

Add an input value to a database value

I am working on a project where I have to add a database value to in input value.
<div>
<div class="price">680</div>
<div class="price">
<input type="number" name="name">
</div>
</div>
In above code 680 will come from the database. Here I want to add an input number to that 680. I am very new to jQuery.
My JavaScript code is
$(document).ready(function() {
var total = 0;
$("input").keyup(function(){
var priceList = $('.price');
$.each(priceList, function(i, price){
total += parseFloat($(price).text());
});
alert(total);
});
});
</script>
In this it outputs "NaN".
In this it outputs "NaN".
You get this message since you're trying to loop through div's and parsing the text of them, when it's empty. You need to loop over input's instead.
You could init the total with the database value then loop through the input's and add the parsed values to total in every iteration.
NOTE: Use input event instead when you track the user input since it's more efficient.
Multiple inputs:
$(document).ready(function() {
var db_val = parseFloat($('.price:first').text());
var total = 0;
$(".price input").on('input', function() {
var total = db_val;
$('.price input').each(function() {
total += parseFloat($(this).val()) || 0;
});
$(".total").text(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="price">680</div>
<div class="price">
<input type="number" name="name">
</div>
<div class="price">
<input type="number" name="name">
</div>
<div class="price">
<input type="number" name="name">
</div>
<div class="total">680</div>
</div>
Single input:
$(document).ready(function() {
var db_val = parseFloat($('.price:first').text());
var total = 0;
$(".price input").on('input', function() {
var total = db_val;
total += parseFloat($(this).val()) || 0;
$(".total").text(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="price">680</div>
<div class="price">
<input type="number" name="name">
</div>
<div class="total">680</div>
</div>
Here you go
var result = 0;
var price = +$('#price').text();
$('input[type="number"]').on('input', function() {
var val = +$(this).val();
result = parseInt(val + price);
$('#price').text(result)
console.log(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="price" id="price">680</div>
<div class="price">
<input type="number" name="name">
</div>

How to check multiple checkboxes with JavaScript?

I have multiple checkboxes
<div class="data">
<span>
<input name="employee" type="checkbox" value="Alex"/>
<label for="employee">Alex</label>
</span>
<span>
<input name="employee" type="checkbox" value="Frank"/>
<label for="employee">Frank</label>
</span>
<span>
<input name="employee" type="checkbox" value="Mark"/>
<label for="employee">Mark</label>
</span>
</div>
How to find all checked checkboxes and create json or array with result of checking?
In case you just want to use pure/vanilla JS, here is an example:
HTML HEAD
<script type="text/javascript">
function getCheckedCheckboxesFor(checkboxName) {
var checkboxes = document.querySelectorAll('input[name="' + checkboxName + '"]:checked'), values = [];
Array.prototype.forEach.call(checkboxes, function(el) {
values.push(el.value);
});
return values;
}
</script>
HTML BODY
<div class="data">
<span>
<input name="employee" type="checkbox" value="Alex"/>
<label for="employee">Alex</label>
</span>
<span>
<input name="employee" type="checkbox" value="Frank"/>
<label for="employee">Frank</label>
</span>
<span>
<input name="employee" type="checkbox" value="Mark"/>
<label for="employee">Mark</label>
</span>
<input type="button" onclick="alert(getCheckedCheckboxesFor('employee'));" value="Get Values" />
</div>
JS Fiddle link: http://jsfiddle.net/dY372/
Try this:
Fiddle
jQuery:
var selected = [];
$('.data input:checked').each(function() {
selected.push($(this).val());
});
Javascript:
var checkboxes = document.getElementsByName('employee');
var selected = [];
for (var i=0; i<checkboxes.length; i++) {
if (checkboxes[i].checked) {
selected.push(checkboxes[i].value);
}
}
Using querySelectorAll:
var checked = document.querySelectorAll('[name="employee"]:checked');
Support: IE9+.
var elements=document.getElementsByName('employee');
should return you an array of the elements you require
DEMO
function checked(){
var items=getElementsByname('checkbox');
var selectedlist=[];
for(var i=0; i<items.length; i++)
{
if(items[i].type=='checkbox' && items[i].checked==true)
selectedlist+=items[i].value+"\n";
}
alert(selectedlist);
}

JQuery to add (math) up values of inputs

I have an html form, and I want to only show the last section of the form if the value of all the other inputs is <= 500. Here is some simple html, mine is slightly more complicated, but it should be the same idea:
<div id="addSection">
<input type="text" id="retire" />
<input type="text" id="child" />
<input type="text" id="military" />
<input type="text" id="nurse" />
<input type="text" id="other" />
</div>
<div id="random" class="hidden">
<input type="text">
</div>
And here my jQuery that doesn't get close to working :)
$('#addSection :input').keyup(function(){
$('#addSection').each(function(){
var totalAmt = 0;
$(this).find('input').each(function(i,n){
totalAmt += parseInt($(n).val(), 10)
});
});
});
//if totalAmt <= 500 then $('#random').show();
Any ideas on how to get it to add as the user goes through the form? Thanks for the help, if you ahve any questions, I will answer quickly.
I'd suggest (on reviewing and subsequently rewriting my previous attempt):
$('#addSection').on('keyup', function(){
var total = $(this).children().map(function(){
return parseInt(this.value,10) || 0;
}).get().reduce(
function(a, b){
return parseInt(a,10) + parseInt(b,10);
});
$('#random').toggle(total <= 500);
}).trigger('keyup');
JS Fiddle demo.
References:
Plain JavaScript:
Array.prototype.reduce().
parseInt().
jQuery:
children().
get().
on().
toggle().
This should do the trick:
$('#addSection :input').keyup(function(){
var totalAmt = 0
$('#addSection :input').each(function(){
totalAmt += parseInt($(this).val(), 10) || 0
});
$('#random').toggle(totalAmt <= 500);
});
Live example: http://jsfiddle.net/ZL3q4/2/
Try this:
<div id="addSection">
<input type="text" id="retire" />
<input type="text" id="child" />
<input type="text" id="military" />
<input type="text" id="nurse" />
<input type="text" id="other" />
</div>
<div id="random" style="display: none;">
<input type="text">
</div>
$('#addSection :input').keyup(function () {
var totalAmt = 0;
$('#addSection :input').each(function (i, n) {
if (parseInt($(n).val(), 10)) totalAmt += parseInt($(n).val(), 10);
});
if (totalAmt > 500) $("#random").show();
else $("#random").hide();
});

how to sum radio button values only one time?

I am using this code to sum values from multiple radio buttons :
$(document).ready(function(){
var total = 50000;
$("input[type=radio]").change(function(){
$("input[type=radio]:checked").each(function(){
if (isNaN($(this).val())) {
total = total;
}
else
total += parseFloat($(this).val());
});
$(".price_amount").text(total);
});
});
the problem is that when user click on a radio button in a group and then select another radio button in that group the new value will be add to this, i want to only add one of the values to the total value.
for example in this group :
<div>
<input type="radio" value="0" name="markuptype" class="pack_radio" checked="checked"><h4>W3C Valid HTML 4.01</h4>
<span class="pack_price">-</span>
</div>
<div>
<input type="radio" value="5000" name="markuptype" class="pack_radio"><h4>W3C Valid XHTML 1.0 Transitional</h4>
<span class="pack_price">5,000</span>
</div>
<div>
<input type="radio" value="15000" name="markuptype" class="pack_radio"><h4>W3C Valid XHTML 1.0 Strict</h4>
<span class="pack_price">15,000</span>
</div>
when first time a user select seconed radio the 5000 will be add to total price, but if he change it to third option, 15000+5000 will be add to total, i want to have only one of them !
The problem seems, to me, that the total var is declared out of the scope of the change callback. This will cause the closure of the change callback to contain the total variable, so it's value will be persisted across subsequent change calls.
If declare the total within this callback, you should be fine:
$("input[type=radio]").change(function(){
var total = 5000; // => declared locally, so initialized at each change.
$("input[type=radio]:checked").each(function(){
if (isNaN($(this).val())) {
total = total;
}
else
total += parseFloat($(this).val());
});
$(".price_amount").text(total);
});
I wrote a simple example demonstrating this recently (although I did it without using jQuery).
Just store the value you add, and then subtract it from the total before adding a new one.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>Radio Test</title>
</head>
<body>
<form action="" method="get" id="myForm">
<fieldset id="myRadioGroup">
<legend>Radios</legend>
<div>
<label> <input type="radio" value="0" name="add" checked> 0 </label>
</div>
<div>
<label> <input type="radio" value="20" name="add"> 20 </label>
</div>
<div>
<label> <input type="radio" value="30" name="add"> 30 </label>
</div>
</fieldset>
<div id="total">45</div>
</form>
<script type="text/javascript">
(function () {
var group = document.forms.myForm.elements.add;
var currentValue = function currentValue () {
for (var i = 0, j = group.length; i < j; i++) {
if (group[i].checked) {
return Number(group[i].value);
}
}
};
var oldValue = currentValue();
var total = document.getElementById('total').firstChild;
var update = function update () {
var current = currentValue();
total.data = Number(total.data) - oldValue + current;
oldValue = current;
};
for (var i = 0, j = group.length; i < j; i++) {
group[i].onchange = update;
}
}());
</script>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<div>
<input type="radio" value="0" name="markuptype" class="pack_radio" checked="checked"><h4>
W3C Valid HTML 4.01</h4>
<span class="pack_price">-</span>
</div>
<div>
<input type="radio" value="5000" name="markuptype" class="pack_radio"><h4>
W3C Valid XHTML 1.0 Transitional</h4>
<span class="pack_price">5,000</span>
</div>
<div>
<input type="radio" value="15000" name="markuptype" class="pack_radio"><h4>
W3C Valid XHTML 1.0 Strict</h4>
<span class="pack_price">15,000</span>
</div>
</body>
<script type="text/javascript">
$(function()
{
$('input:radio').change(function()
{
var total = 50000;
$('input:radio:checked').each(function()
{
if (isNaN(this.value))
total = total;
else
total += parseFloat(this.value);
});
$('.price_amount').text(total);
});
});
</script>
</html>

Categories

Resources