简体   繁体   中英

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

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

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="">

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);
});

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" />

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="">

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="">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM