如何使用javascript和/或jquery添加表单字段值

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

本文关键字:添加 表单 字段 jquery 何使用 javascript      更新时间:2023-09-26
嗨,我

有一个表单和一个脚本,在我制作的形式中添加和乘以值效果很好......唯一的问题是它不会添加十进制数字。 有什么方法可以解决这个问题吗?

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

我在你的 jsfiddle 示例中做了一些更改......请看一看。它正在按照您想要的方式工作

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

好吧,使用 parseInt 而不是 parseFloat 会导致计算错误......但现在我已经更新了上面的链接...请看一看。

使用+ 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
    })
});

演示