i need to sum the values from multiple SELECTS and INPUTS, this is what i have so far:
HTML
<label>Item#1</label>
<select name="price[]" id="sel_1">
<option value="">Options</option>
<option value="4.00">Small</option>
<option value="8.00">Medium</option>
</select>
<br>
<label>Item#2</label>
<select name="price[]">
<option value="">Options</option>
<option value="4.00">Small</option>
<option value="8.00">Medium</option>
</select>
<br>
<label>Item#3</label>
<select name="price[]">
<option value="">Options</option>
<option value="4.00">Small</option>
<option value="8.00">Medium</option>
</select>
<br>
<label>Item#4</label>
<input type="checkbox" value="1.00" id="price[3]" name="price[]">
<br>
<label>Item#5</label>
<input type="checkbox" value="2.00" id="price[3]" name="price[]">
<br>
<label>Item#6</label>
<input type="checkbox" value="3.00" id="price[3]" name="price[]">
<br> <span id="usertotal"> </span>
JQUERY
$('input:checkbox').change(function () {
var tot = 0;
$('input:checkbox:checked').each(function () {
tot += Number($(this).val());
});
tot += Number($('#sel_1').val());
$('#usertotal').html(tot)
});
$('#sel_1').change(function () {
$('input:checkbox').trigger('change');
});
As you can notice it only sum the value from first select i need it too sum from all the selects.
DEMO: http://jsfiddle.net/B9ufP/
Try this:
(I simplified a bit your code)
(function ($) {
var $total = $('#usertotal');
$('input,select:selected').on('change', function () {
var tot = 0;
$(':checked, select').each(function () {
tot += ~~this.value;
});
$total.html(tot)
});
}(jQuery))
Demo here
If you want to be fancy, you can also use Array.prototype.reduce to sum up the values.
Note that if you have decimals, use parseFloat.
var total = [].reduce.call($('select, :checkbox:checked'), function (pv, cv) {
return parseFloat(pv.value) + parseFloat(cv.value);
});
Related
I can't seem to figure out how to sum the values of various field types in a form. I have some select fields like this:
<select name="age">
<option value="">- Select -</option>
<option value="1" class="">30-34</option>
<option value="2">35-39</option>
</select>
And some radio buttons:
<p>Do you smoke?</p>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="2"> Yes</label><br>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label>
But how would I add the selections all up? I can find solutions for adding values of just inputs, or just radios, or just selects. But not all together.
I'd use jQuery if I have to.
[EDIT] I should have said, I'd like to output the total value to the user, perhaps inside a element.
Could clean this up a bit, but an example of using the FormData interface to add up all values in a form: https://developer.mozilla.org/en-US/docs/Web/API/FormData
function getValues() {
let myForm = document.getElementById('myForm');
let formData = new FormData(myForm);
let total = 0;
for (var value of formData.values()) {
total += parseInt(value);
}
document.getElementById("total").innerHTML = total;
console.log(total);
}
<form id="myForm" name="myForm">
<div>
<label for="age">What is your age?</label>
<select name="age">
<option value="">- Select -</option>
<option value="1" class="">30-34</option>
<option value="2">35-39</option>
</select>
</div>
<div>
<label for="riskSmoke">Do you smoke?</label>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="2"> Yes</label>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label>
</div>
</form>
<button onclick="getValues()">Get Values</button>
<p>Total:</p>
<div id="total"></div>
You can use constructor FormData.
An HTML <form> element — when specified, the FormData object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values. It will also encode file input content.
You could add a key/value pair to this using FormData.append:
formData.append('username', 'Chris');
I assume that you mean adding the values of the selected elements and that you use some trigger in this case I use a button. To make it work select options that have values
Please try this option
const button = document.querySelector("button");
button.addEventListener("click", () => {
const age = document.querySelector("select");
const riskSmoke = document.querySelector('input[name="riskSmoke"]:checked');
if (age && age.value && riskSmoke) {
const ageValue = +age.value;
const riskSmokeValue = +riskSmoke.value;
console.log(ageValue + riskSmokeValue);
}
});
<select name="age">
<option value="">- Select -</option>
<option value="1" class="">30-34</option>
<option value="2">35-39</option>
</select>
<p>Do you smoke?</p>
<label><input type="radio" name="riskSmoke" value="2" /> Yes</label><br />
<label><input type="radio" name="riskSmoke" value="0" /> No</label>
<button>Click</button>
Without jQuery and for selecting specific values:
function getValues() {
var ageValue = Number(document.querySelector("select[name=age]").value);
console.log('age value: ' + ageValue);
var smokeValue = Number(document.querySelector('input[name="riskSmoke"]:checked').value);
console.log('smoke value: ' + smokeValue);
console.log('age + smoke: ' + (ageValue + smokeValue));
}
<select name="age">
<option value="">- Select -</option>
<option value="1" class="">30-34</option>
<option value="2">35-39</option>
</select>
<p>Do you smoke?</p>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="2"> Yes</label><br>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label>
<p>
<button onclick="getValues()">Get Values</button>
jQuery seems to be a bit of a overkill. In order to get the sum of the options and inputs, you may first get the value of the option in the select tag, and then add to the value of the selected radio input as such:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Your Title Here</title>
</head>
<body>
<select name="age" id="someId">
<option value="">- Select -</option>
<option value="1" class="">30-34</option>
<option value="2">35-39</option>
</select>
<p>Do you smoke?</p>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="2"> Yes</label><br>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label><br>
<button onclick="CalculateValue()">Calculate</button>
<script>
let ageRangePicker = null, riskSmokeOptions = null;
function CalculateValue(){
ageRangePicker = document.getElementById("someId");
if(ageRangePicker.value !== ""){
let sum = Number(ageRangePicker.value);
riskSmokeOptions = document.getElementsByName("riskSmoke")
for(i = 0; i < riskSmokeOptions.length; i++) {
if(riskSmokeOptions[i].checked)
sum += Number(riskSmokeOptions[i].value);
}
alert("Your risk is: " + sum);
}
else{
alert("Select an age range");
}
}
</script>
</body>
</html>
I wrap in a form with an ID and sum on all input, making sure only to count checked radios and checkboxes
const sumValues = () => {
let val = 0;
$("#myForm :input").each(function() {
if (this.type === "radio" || this.type === "checkbox")
val += this.checked ? +this.value : 0;
else val += +this.value; // cast to number
})
$("#total").text(val)
};
$(function() {
$("#myForm").on("change", sumValues).change(); //when page loads
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
<select name="age">
<option value="">- Select -</option>
<option value="1" class="" selected>30-34</option>
<option value="2">35-39</option>
</select>
<p>Do you smoke?</p>
<label for="riskSmoke"><input type="radio" checked name="riskSmoke" value="2"> Yes</label><br>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label>
<br/>Total: <span id="total" />
</form>
Plain JS
const sumValues = () => {
let val = 0;
[...document.getElementById("myForm").querySelectorAll("input, select, textarea")].forEach(function(elem) {
if (elem.type === "radio" || elem.type === "checkbox")
val += elem.checked ? +elem.value : 0;
else val += +elem.value; // cast to number
})
document.getElementById("total").textContent = val;
};
window.addEventListener("load", function() {
document.querySelector("#myForm").addEventListener("change", sumValues)
sumValues()
})
<form id="myForm">
<select name="age">
<option value="">- Select -</option>
<option value="1" class="" selected>30-34</option>
<option value="2">35-39</option>
</select>
<p>Do you smoke?</p>
<label for="riskSmoke"><input type="radio" checked name="riskSmoke" value="2"> Yes</label><br>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label>
<br/>Total: <span id="total" />
</form>
With jQuery, you can listen for the change event and use both the jQuery .serializeArray() and the array .reduce() method to get the total:
$('form').on('change', function() {
let totalScore = $(this).serializeArray().reduce((a, f) => a += +f.value, 0);
//output to a predefined element
$('#output').text( totalScore );
})
.change();
Here is how you may define an output element:
<div class="output">
<label>Total Score: </label>
<span id="output"></span>
</div>
Note that this will give a running total and there's no need to click any button or to trigger any event other then the actions needed to make choices on the various form elements.
$('form').on('change', function() {
let totalScore = $(this).serializeArray().reduce((a, f) => a += +f.value, 0);
//console.log( totalScore );
$('#output').text( totalScore );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post">
<select name="age">
<option value="">- Select -</option>
<option value="1" class="">30-34</option>
<option value="2">35-39</option>
</select>
<p>Do you smoke?</p>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="2"> Yes</label><br>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label>
</form>
<div class="output">
<label>Total Score: </label>
<span id="output"></span>
</div>
Put a button below at the bottom of your HTML and make a function something like this:
const radioControls = document.querySelectorAll('.radio-btn');
const selectControl = document.querySelectorAll('.select');
let dataTransferObject = {
radioValue: 0,
selectValue: 0
};
let sum = 0;
function collectValues() {
for(let control of radioControls) {
if (control.checked) {
dto.radioValue = control.value
}
}
dto.selectValue = selectControl[0].value;
for(let attr of Object.values(dto)) {
sum += parseInt(attr);
}
}
Then your button simply calls this function, I would imagine this would all be contained in a form of some sort:
<button onclick="collectValues()">Submit</button>
Now the variable sum holds the accumulated value.
I have the following code that is not working the way i want it to, apparently, am trying to multiply select option data attributes with input text area values but instead select option value are being used. I need to figure out why its so.
Here is my code;
<input id="count" min="1" value="1" class ="txtMult form-control" type="number" name="txtEmmail" />
<input type="text" value="" class ="txtMult" name="txtEmmail"/>
<span class="multTotal"></span>
<select class="selectpicker">
<option value="1" data-cubics='1'>multiply with 1</option>
<option value="5" data-cubics='5'>multiply with 5</option>
</select>
<span id="grandTotal">250</span>
$(function(){
$('.txtMult').change(function(){
var p=$(this).parent().parent()
var m=p.find('input.txtMult')
var mul=parseInt($(m[0]).val()*$(m[1]).val()).toFixed(2)
var res=p.find('.multTotal')
res.html(mul);
var total=0;
$('.multTotal').each(function(){
total+=parseInt($(this).html());
})
parseInt(total).toFixed(2);
$('#grandTotal').html(parseInt(total).toFixed(2));
});
})
$('.selectpicker').change(function() {
calcVal();
});
function calcVal(){
$(this).data('cubics')*$('.multTotal').html();
$("#grandTotal").html($(this).data('cubics')*$('.multTotal').html())
}
// call on document load
calcVal();
Don't use .html() to get the values, use .text() instead.
You need to get the selected option using this:
$("#grandTotal").html($(this).children(':checked')
$(function() {
$('.txtMult').change(function() {
var p = $(this).parent().parent()
var m = p.find('input.txtMult')
var mul = parseInt($(m[0]).val() * $(m[1]).val()).toFixed(2)
var res = p.find('.multTotal')
res.html(mul);
var total = 0;
$('.multTotal').each(function() {
total += parseInt($(this).text());
})
parseInt(total).toFixed(2);
$('#grandTotal').html(parseInt(total).toFixed(2));
});
})
$('.selectpicker').change(calcVal);
function calcVal() {
$("#grandTotal").html($(this).children(':checked').data('cubics') * $('.multTotal').text().trim())
}
// call on document load
calcVal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>
<input id="count" min="1" value="1" class="txtMult form-control" type="number" name="txtEmmail" />
<input type="text" value="" class="txtMult" name="txtEmmail" />
<span class="multTotal"></span>
<select class="selectpicker">
<option value="1" data-cubics='1'>multiply with 1</option>
<option value="5" data-cubics='5'>multiply with 5</option>
</select>
<span id="grandTotal">250</span>
</div>
</div>
i am trying to find SUM of some number based on check box and select option .
here is my code
<div class="container">
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<label>
<input type="checkbox" value="10">10
</label>
</div>
<input id="total" placeholder="total" />
And my script is
function updateTotal(){
var total = 0;
$(".container input[type='checkbox']").each(function(){
if($(this).is(":checked")){
var multiplier = Number($(this).parent().prev().val());
var checkboxAmount = Number($(this).val());
total += multiplier * checkboxAmount;
}
});
$("#total").val(total);
}
$("select, input[type='checkbox']").on("change", updateTotal);
The above script is just working fine give html code . But when keep my checkbox first and select option next , then this script will not give any output
i wanted my HTML code like this , then script should be work fine for this
<div class="container">
<label>
<input type="checkbox" value="10">10
</label>
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<input id="total" placeholder="total" />
any help , code coppied from here
Try this one-
function updateTotal() {
var total = 0;
$(".container").each(function () {
var checkbox = $(this).find("input[type='checkbox']");
var select = $(this).find("select");
if (checkbox.is(":checked")) {
total += Number($(this).find("input[type='checkbox']").val()) * Number(select.val());
}
});
}
I have this code:
$(document).ready(function(){
$('.container select').each(function(){
$(this).on('change', function(){
var selectedVal = $(this).val();
//console.log(selectedVal);
});
});
$('input').on('change', function () {
var sum = 0;
$('input').each(function() {
sum += Number($(this).val());
});
$('.total span').html(sum);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
<div class='full'>
<input type='number' value=''>
<select name='select1'>
<option value='a1'>A1</option>
<option value='a2'>A2</option>
</select>
</div>
<div class='full'>
<input type='number' value=''>
<select name='select2'>
<option value='a1'>A1</option>
<option value='a2'>A2</option>
</select>
</div>
<div class='full'>
<input type='number' value=''>
<select name='select3'>
<option value='a1'>A1</option>
<option value='a2'>A2</option>
</select>
</div>
<div class='total'>
Total nr: <span>5(2 A1, 3 A2)</span>
</div>
</div>
Is it possible that on change of the select and the input of type number to modify the total number like in the code above using JavaScript/jQuery?
Can anyone help me with this please.
On every change on the inputs or select fields I need to calculate total number of A1 and total number of A2. Hope this make sense. And display them beside the total number.
JSFiddle
We can't give you the full code but I tried to provide some logic for what you want.I think you want some thing like this:
//create a json to collect the sum of numbers
var number = {
a1: 0,
a2: 0,
a1_count:0,
a2_count:0
};
//check in select change
$(".select").change(function() {
//flush previous calculation before using again
number.a1=0,number.a2=0,number.a1_count=0,number.a2_count=0;
//check all the select value and get the corresponding input value
$(".select").each(function() {
var valueType = $(this).val();
if (valueType == "a1") {
number[valueType+"_count"]=number[valueType+"_count"]+1;
number[valueType] = number[valueType] + parseInt($(this).prev().val()||0);
} else if (valueType == "a2") {
number[valueType+"_count"]=number[valueType+"_count"]+1;
number[valueType] = number[valueType] + parseInt($(this).prev().val()||0);
}
});
$("#total").html('Total:'+(number.a1+number.a2)+',A1:'+number.a1+'('+number.a1_count+'),A2:'+number.a1+'('+number.a2_count+')');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
<div class='full'>
<input type='number' value=''>
<select name='select1' class='select'>
<option value='a1'>A1</option>
<option value='a2'>A2</option>
</select>
</div>
<div class='full'>
<input type='number' value=''>
<select name='select2' class='select'>
<option value='a1'>A1</option>
<option value='a2'>A2</option>
</select>
</div>
<div class='full'>
<input type='number' value=''>
<select name='select3' class='select'>
<option value='a1'>A1</option>
<option value='a2'>A2</option>
</select>
</div>
<div class='total' id="total">
</div>
</div>
This will work for any arbitrary list in the select.
function change() {
var res = {}, fulls = $('.container .full');
fulls.each(function(index){
var selected = $(this).find('select > option:selected').text();
if (! res[selected]) res[selected] = 0;
res[selected] += 1*$(this).find('input[type="number"]').val();
});
var detail = "", total = 0;
for(prop in res) {
if (res.hasOwnProperty(prop)) {
try {
var val = 1*res[prop];
detail += ", "+val+" "+prop;
total += val;
}catch(e){}
}
}
$('.total > span').text(""+total+" ("+detail.substr(2)+")");
}
$().add('.container .full input[type="number"]')
.add('.container .full select[name^="select"]')
.on('change', change);
I have a simple jquery calculator:
<p class="price" data-base-price="50">$<span>80</span></p>
<select name="s1" class="price-option">
<option value="1" data-price="10">Item 1</option>
<option value="2" data-price="20">Item 2</option>
</select>
<select name="s2" class="price-option">
<option value="1" data-price="30">Item 3</option>
<option value="2" data-price="40">Item 4</option>
</select>
<input type="text" name="price-option-input" id="price-option-input">
Javascript:
$(document).ready(function () {
$('.price-option').change(function(){
var price = parseInt($('.price').data('base-price'));
$('.price-option').each(function(i, el) {
price += parseInt($('option:selected', el).data('price'));
});
price += parseInt($('#price-option-input').val());
$('.price span').text(price);
});
});
This calculator is working, but the problem is when I enter value for text input the result in price is not updating dynamically (I need to choose another option in selector for result updating)
You have to add keyUp event
calculate = function(){
var price = parseInt($('.price').data('base-price'));
$('.price-option').each(function(i, el) {
price += parseInt($('option:selected', el).data('price'));
});
price += parseInt($('#price-option-input').val());
$('.price span').text(price);
}
$(document).ready(function () {
$('#price-option-input', .price-option').change(calculate);
$('#price-option-input', .price-option').keyup(calculate);
});
I think it´s worth it to explain that change event is fired when you unselect the input, or, in number type, when you use the up/down buttons.
You can add a button to do the computation, triggering the change event.
Example:
$("button").on("click", function() {
$('.price-option').trigger("change");
});
Or, you can listen the keyup event from the input and at the enter key press, do the computation. The question is: when do you want to do the computation? With the answer, listen to the proper event and do the computation.
I believe you just need to use .html because that will set the inner HTML:
$('.price span').html(price);
And for future reference, multi-selectors like that aren't near as efficient as something like this:
$('.price').find('span').html(price);
I have fixed your code and it works fine now http://plnkr.co/edit/pWSEimrKkA200jQK9w5a?p=preview
HTML:
<p class="price" data-base-price="50">$<span>80</span></p>
<select name="s1" class="price-option">
<option value="1" data-price="10">Item 1</option>
<option value="2" data-price="20">Item 2</option>
</select>
<select name="s2" class="price-option">
<option value="1" data-price="30">Item 3</option>
<option value="2" data-price="40">Item 4</option>
</select>
<input type="text" name="price-option-input" id="price-option-input" onchange='updatePrice()'>
JS:
function updatePrice(){
var price = parseInt($('.price').data('base-price'));
console.log(price);
$('.price-option').each(function(i, el) {
price += parseInt($('option:selected', el).data('price'));
});
price += parseInt($('#price-option-input').val());
$('.price span').text(price);
}