简体   繁体   中英

How to add form field values using javascript and/or jquery?

Hi I have a form and a script and it works great to add and multiply values in a form i made...only problem is it wont add decimal numbers. Any way to fix this?

<form>

<input type="text" id="1" name="1" >
<input type="text" id="2" name="2" value="1.11">
<input type="text" id="A" name="A">
<input type="text" id="B" name="B">
<input type="text" id="total" name="total">

<button type="button" id="calculate" name="button">Calculate</button>

</form>


<script>
$(document).ready(function(){
    $('#calculate').on('click',function(){
        var v1 =  $('#1').val();  // take first text box value
        var v2 =  $('#2').val();  // take second hidden text box value
        $('#A').val(parseInt(v1)+parseInt(v2)); // set value of A
        var aval = (parseInt($('#A').val()) * parseFloat(.08)); // calculate value of b
        $('#B').val(aval);// set value of B
        var totalval = parseInt($('#A').val()) + parseFloat(aval);
        //calculate value for total
        $("#total").val(totalval); // set total
    })

});
</script>

http://jsfiddle.net/1s3hoeqw/2/

convert string to number using + operator

$(document).ready(function () {
    $('#calculate').on('click', function () {
        var v1 = $('#1').val(); // take first text box value
        var v2 = $('#2').val(); // take second hidden text box value
        $('#A').val((+v1) + (+v2)); // set value of A
        var aval = $('#A').val() * .8; // calculate value of b
        $('#B').val(aval); // set value of B
        var totalval = (+$('#A').val()) + aval;
        //calculate value for total
        $("#total").val(totalval); // set total
    })

});

DEMO

I have make some changes in your jsfiddle example....please take a look at it....it's working as you want

`http://jsfiddle.net/1s3hoeqw/11/`

well, using parseInt instead of parseFloat was causing errors in calculations...but now I have updated above link...please take a look at.

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