How to calculate form fields values to update hidden field value? - javascript

I want to know how to calculate the input values of the following fields
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
And update the span text and the hidden field value
TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">
Thanks in advance

This should do what you want to achieve:
function displaySum () {
var sum = 0;
// iterate over the input fields
$('.auto-sum').each(function () {
var value = $(this).val() || 0;
var number = parseInt(value, 10); // parse the input value to an integer
if (isNaN(number)) {
number = 0;
}
sum += number; // add the value to the sum
});
// set the value of the two elements
$('#amountTotal').text(sum);
$('#total').val(sum);
}
// whenever the value of one of the input fields changes, call the displaySum function
$('.auto-sum').on('change, keyup', displaySum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">

I tried with blur method for after mouseleave from input and check all input values and added ! Then update to wanted element !!
$("input").on("blur",function(){
var total = 0;
$("[type='text']").each(function(){
if($(this).val() != "") {
total += parseInt($(this).val());
}
});
$("#amountTotal").text(total);
$("#total").val(total);
});

Try with query each() function .Use with parseFloat convert the string to number .for real time update do with keyup event
$('.auto-sum').keyup(function(){
var a=0;
$('.auto-sum').each(function(){
a+=parseFloat($(this).val())
})
$('#amountTotal').text(a|0)
$('#total').val(a|0)
console.log($('#total')[0].outerHTML)//its show the hidden field value
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum" value="2" >
<input type="text" name="score2" class="auto-sum" value="5">
<input type="text" name="score3" class="auto-sum" value="5">
TOTAL <span id="amountTotal" >0 </span>
<input id="total" type="hidden" name="total" value="">

You can use <input type="number" /> inputs to force values entered to be a number.
From there you can call jQuery with the query selector input.auto-sum to get all of the input elements with the class auto-sum
Using the each function you can add the numeric to an accumulator to get the total.
You can then use jQuery with the query selectors needed to set any other elements on the page with the Total value.
function getTotal() {
var total=0;
$('input.auto-sum').each(function(i,e)
{
total += Number($(e).val());
});
$('#amountTotal').text(total);
$('#total').val(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Score 1: <input type="number" name="score1" class="auto-sum"><br />
Score 2: <input type="number" name="score2" class="auto-sum"><br />
Score 3: <input type="number" name="score3" class="auto-sum"><br />
TOTAL: <span id="amountTotal">0 </span><br />
<input id="total" type="hidden" name="total" value="">
<input type="button" id="btnTotal" onclick="getTotal()" value="Get Total" />

Please try this one.
$('.auto-sum').on('change',function(){
var totalvalue=0;
$('.auto-sum').each(function(a,b){
totalvalue=totalvalue+parseInt(($(b).val()=='' || isNaN($(b).val()))?0:$(b).val());
});
$('#amountTotal').text(totalvalue);
$('#total').val(totalvalue);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
TOTAL <span id="amountTotal">0</span>
<input id="total" type="hidden" name="total" value="">

<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
<input type="button" id="calculator" value="Caculate">
$("#calculator").on("click",function (){
var result=0;
var sum_fields=$(".auto-sum");
for(var i=0;i<sum_fields.length;i++){
if(!isNaN(sum_fields[i]) && sum_fields[i]>0){
result += sum_fields[i];
}
}
$("#amountTotal").text(result);
$("#total").val(result);
});
Create array for the fields and loop through them
Check if it not a NaN and more than 0 add them to the result then after the loop attach the result to the hidden field and as a span text

I post this as an answer because the comment areas are to small
At first i think it´s an good idea to write
<input type = "number">
when you don´t want to display the small arrows look at this solution:
https://css-tricks.com/snippets/css/turn-off-number-input-spinners/
the keyup event ist the best way to "live" display the total sum
At last take a look at vue.js
This is the best solution for this scenario.

if you're interested in a pure javascript solution:
All inputs have an oninput event attribute that fires when the input is changed.
You can attach an event handler to the event like so:
<input oninput="updateTotal" />
where updateTotal is a function declared in your script:
function updateTotal { /* code that updates the total */ }
OR if you select the input in your script then you can attach the event handler like this:
selectedInput.oninput = function updateTotal () {
...
}
Here's my implementation that selects all the inputs with the class "auto-sum", assigns the event handler to each of them and updates the code by looping over each input's value attribute:
https://jsfiddle.net/billy_reilly/5dd24v81/2/

function displaySum () {
var sum = 0;
// iterate over the input fields
$('.auto-sum').each(function () {
var value = $(this).val() || 0;
var number = parseInt(value, 10); // parse the input value to an integer
if (isNaN(number)) {
number = 0;
}
sum += number; // add the value to the sum
});
// set the value of the two elements
$('#amountTotal').text(sum);
$('#total').val(sum);
}
// whenever the value of one of the input fields changes, call the displaySum function
$('.auto-sum').on('change, keyup', displaySum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">

Related

Finding the value of multiple input boxes

I'm building a multiple quantity selector for my store. Image below:
On the site, the price of the product updates based on the quantity added. 10 products = 10% off etc. I'd like to be able to display this price change as and when the user edits any one of the input boxes in the quantity selector.
The input fields are built like this:
<div data-value="S" data-varientid="8195426353207" class="swatch-element swatch-element-2 size s available">
<input id="swatch-0-s" data-variant-id="variant_8195426353207" type="checkbox" name="option-0" value="S">
<label for="swatch-0-s">
S
<img class="crossed-out" src="//cdn.shopify.com/s/files/1/0020/2188/3959/t/2/assets/soldout.png?5180939831627851747" alt="">
</label>
<input id="qty" name="quantity" class="swatchinput" placeholder="0" value="0" type="text">
</div>
I'm able to watch the input boxes for change by doing the below:
var qty = $('.swatchinput');
$('.swatchinput').on('paste keyup', function() {
console.log(qty);
});
However, this returns the information about the element rather than the contents. I'm also unsure of the best way to then add the contents of the various input fields together to reach the total quantity.
You could also use the Array reduce method to do this. Select all the inputs, get the array, then reduce their values into the sum.
var total = $('.swatchinput').get().reduce(function(total, input){
return total + parseInt(input.value || '0');
}, 0);
console.log(total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="quantity" class="swatchinput" placeholder="0" value="1" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="2" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="3" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="4" type="text">
This needs to be
var qty = $('.swatchinput').val();
not
var qty = $('.swatchinput');
As for your second question,
loop each of these inputs, getting the value, then add them up with a total. Initialize the total OUTSIDE of the loop also so it doesn't overwrite it.
Something like this?
var total = 0;
$('.switchinput').each(function(){
total += $(this).val();
});
console.log(total);
To get the value of an element in jQuery, use .val():
http://api.jquery.com/val/
.each loops through each matched element and runs a function on that element (accessible through 'this')
http://api.jquery.com/each/

HTML form:input calculate 2 fields

I'm using spring mvc for my form which has the tag
<form:input type="number" class="value1" id="value1" path="commandName.object.field1" />
<form:input type="number" class="value1" id="value1" path="commandName.object.field2" />
<input type="text" disabled="disabled" id="result" />
I read some questions in regards to calculations and even found a js fiddle:
http://jsfiddle.net/g7zz6/1125/
how do i calculate 2 input fields and put results in 3rd input field
but it doesn't work when the input tag is form:input. Is it possible to do auto calculation of the 2 form:input fields upon keyin and update the 3rd input?
Here you go
HTML
<input type="text" class="input value1">
<input type="text" class="input value2 ">
<input type="text" disabled="disabled" id="result">
JS
$(document).ready(function(){
$('input[type="text"]').keyup(function () {
var val1 = parseInt($('.value1').val());
var val2 = parseInt($('.value2').val());
var sum = val1+val2;
$("input#result").val(sum);
});
});
Fiddle https://jsfiddle.net/1sbvfzcc/
$(document).ready(function(){
var val1 = +$(".value1").val();
var val2 = +$(".value2").val();
$("#result").val(val1+val2);
});
$('.input').blur(function(){
var val1 = +$(".value1").val();
var val2 = +$(".value2").val();
$("#result").val(val1+val2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="input value1" value="20">
<input type="text" class="input value2" value="30">
<input type="text" disabled="disabled" id="result">
Please check the code this might help you understand why your code is not working.
You are using document ready function which is not able to get the value as no default value for input box.
I have added a new blur function which will calculate the value on change of input box
Try this your form tag syntax was wrong
$('form').on('keyup' ,'.value1', function(){
var k=0;
$('.value1').each(function(){
k +=parseFloat($(this).val()|0);
})
$('input:text').val(k)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="number" class="value1" id="value1" path="commandName.object.field1" />
</form>
<form>
<input type="number" class="value1" id="value1" path="commandName.object.field2" />
</form>
<input type="text" disabled="disabled" id="result" />

jQuery, How can I disable all others input field if sum of all values is greater "x"

jQuery, disable all others input on same class if sum of all value more than x
How to disable "HTML input box" which not empty node when the sum of any input box has value. I want to calculate some of any input field and disable any others if the sum is greater than x.
For example to this code:
second field = 5
forth field = 10,
sum is 15
first field and third field should be disabled
$('.inputReward').on('input',function() {
//$(this).next().not(this).prop('disabled', this.value.length)
var sum=0;
$('.inputReward').each(function () {
sum += +$(this).val();
if(sum>15) //15 is maximum value
$(this).next().not(this).prop('disabled', true);
else
$(this).next().not(this).prop('disabled', false);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" name="sRewards" value="" class="inputReward" />
<input type="number" name="sReward1" value="" class="inputReward" />
<input type="number" name="sReward2" value="" class="inputReward" />
<input type="number" name="sReward3" value="" class="inputReward" />
But now i just can do only disable all next input field of a last not empty node.
I think this is my best solution :)
$('.inputReward').on('input',function() {
//$(this).next().not(this).prop('disabled', this.value.length)
var sum=0;
$('.inputReward').each(function () {
sum += +$(this).val();
});
if(sum>=15)
$(this).siblings().not(this).prop('disabled', true);
else
$(this).siblings().not(this).prop('disabled', false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" name="sRewards" value="" class="inputReward" />
<input type="number" name="sReward1" value="" class="inputReward" />
<input type="number" name="sReward2" value="" class="inputReward" />
<input type="number" name="sReward3" value="" class="inputReward" />

How to add onChange function for all HTML form fields

My HTML Page has 10 Text Fields.
Currently no onChange EVENT is available for all ten fields.
<input type="text" name="text1" value="1">
<input type="text" name="text2" value="2">
<input type="text" name="text3" value="3">
<input type="text" name="text4" value="">
<input type="text" name="text5" value="">
<input type="text" name="text6" value="">...
Now, I want to add onChange Function in all fields whose field is of input type.
How do I add onChange or onBlur even in my JS section?
In onChange function, I will call ajax function which will validate whether the field has Hacking Keywords.
So my question is:
How do I add onChange function for all form fields. My field should dynamically be like below:
<input type="text" name="text1" value="1" onChange="javascript:fnName" onBlur="javascript:fnName" >
<input type="text" name="text2" value="2" onChange="javascript:fnName" onBlur="javascript:fnName" >
<input type="text" name="text3" value="3" onChange="javascript:fnName" onBlur="javascript:fnName" >
<input type="text" name="text4" value="" onChange="javascript:fnName" onBlur="javascript:fnName" >
<input type="text" name="text5" value="" onChange="javascript:fnName" onBlur="javascript:fnName" >
<input type="text" name="text6" value="" onChange="javascript:fnName" onBlur="javascript:fnName" >
<input type="text" name="text7" value="" onChange="javascript:fnName" onBlur="javascript:fnName" >
This can be achieved with vanilla JavaScript as zvona suggests.
Here is a simple loop to mock an HTML5 placeholder. <<DEMO>>
var prompt = 'Type something here';
var textFields = document.querySelectorAll('input[name^="text"]');
var index = 0;
for (index = 0; index < textFields.length; ++index) {
var textField = textFields[index];
textField.addEventListener('change', onChangeHandler);
textField.addEventListener('focus', onFocusHandler);
textField.addEventListener('blur', onBlurHandler);
textField.value = prompt;
console.log(textField);
}
function onChangeHandler() {
// Do something...
}
function onFocusHandler() {
if (this.value === prompt) {
this.value = '';
}
}
function onBlurHandler() {
if (this.value === '') {
this.value = prompt;
}
}
you can try to give change function to your form using
$('.form :input').change(function(e){
$('#log').prepend('<p>Form changed ' + $(e.target).attr('id') + '</p>')
});
Demo1
Demo2
[].forEach.call(document.querySelectorAll("input"), function(input) {
input.addEventListener("change", fnName, false);
input.addEventListener("blur", fnName, false);
});
getElementsByTagname() gets you an array of all input. Interate over them and addEventListener.
Or use jQuery's $('input').on('change'...)
Try something like:
var inputList = document.getElementsByTagName("input");
for(var i=0;i<inputList.length;i++){
inputList[i].onchange = function(){
//function here
}
inputList[i].onblur = function(){
//function here
}
}

How to set sum value on text feild when second value is set text?

This is my demo cord.
<input type="text" id="my_input1" />
<input type="text" id="my_input2" />
<input type="text" id="total" />
<input type="button" value="Add Them Together" onclick="doMath();" />
<script type="text/javascript">
function doMath()
{
// Capture the entered values of two input boxes
var my_input1 = document.getElementById('my_input1').value;
var my_input2 = document.getElementById('my_input2').value;
// Add them together and display
var sum = parseFloat(my_input1) + parseFloat(my_input2);
document.getElementById('total').value=sum;
}
I want to work this function when my_input2 is enter it's value. Just like onclick method for button is there any event to set value to total tetxfeild after key release event?
<script type="text/javascript">
$(document).ready(function () {
$("#my_input2").blur(function () {
var sum = parseInt($("#my_input1").val()) + parseInt($("#my_input2").val());
$("#total").val(sum);
});
});
</script>
<div>
<input type="text" id="my_input1" />
<input type="text" id="my_input2" />
<input type="text" id="total" />
<input type="button" value="Add Them Together" />
</div>
And also u should frame ur question correctly bcz u have added code in button click and asking us it should work after leaving textbox
Put onkeyup() on second input field this will fire your function.
Something like that:
<input type="text" id="my_input2" onkeyup="doMath();" />
try this
<input type="text" id="my_input2" onchange="doMath();" />

Categories

Resources