0

我有一个带有输入类型文本字段、选择菜单和复选框的表单。每个表单域都存储一个数值,具体取决于用户输入、选择或检查的内容。

是否可以使用 jQuery 实时添加这三个值并在第四个表单字段中显示总数?

这是我的 JSFiddle,如果所有字段都是输入类型的文本,它就可以工作,尽管我仍然无法将总值放在第四个表单字段中:

jQuery

$('input').keyup(function(){ // run anytime the value changes

    var firstValue = parseFloat($('#first').val()); // get value of field
    var secondValue = parseFloat($('#second').val()); // convert it to a float
    var thirdValue = parseFloat($('#third').val());

    $('#added').html(firstValue + secondValue + thirdValue); // add them and output it

    var firstValueComplex = parseFloat($('#firstComplex').val()); // get value of field
    var secondValueComplex = parseFloat($('#secondComplex').val()); // convert it to a float
    var thirdValueComplex = parseFloat($('#thirdComplex').val());

    $('#addedComplex').html(firstValueComplex + secondValueComplex + thirdValueComplex); // add them and output it
});

HTML

<input id="second" value="0"></input><br />

<input id="third" value="0"></input><br />
<b>Total:<span id="added"></span></b><br />

<input id="firstComplex" value=""></input><br />

<select id="secondComplex">
    <option value="0" selected>0</option>
    <option value="15">15</option>
    <option value="30">30</option>
</select><br>

<input type="checkbox" id="thirdComplex" value="16"> Add Value<br>
<b>Total:<span id="addedComplex"></span></b>

<input id="total" value="<span id=addedComplex></span>"></input>

http://jsfiddle.net/nathonjones/c3n5vc8f/3/

希望你能帮忙,谢谢。新泽西州

4

1 回答 1

1

您想在多个输入上绑定多个事件,可以这样完成:

$(':input').on('change keyup check',function () { // run anytime the value changes
    var firstValue = parseFloat($('#first').val()); // get value of field
    var secondValue = parseFloat($('#second').val()); // convert it to a float
    var thirdValue = parseFloat($('#third').val());
    $('#added').html(firstValue + secondValue + thirdValue); // add them and output it

    var firstValueComplex = parseFloat($('#firstComplex').val()) || 0; // get value of field
    var secondValueComplex = parseFloat($('#secondComplex').val()); // convert it to a float
    var thirdValueComplex = $('#thirdComplex').is(':checked') ? parseFloat($('#thirdComplex').val()) : 0;

    $('#addedComplex').html(firstValueComplex + secondValueComplex + thirdValueComplex); // add them and output it
    $('#total').val(firstValueComplex + secondValueComplex + thirdValueComplex)
});

jsFiddle 示例

另请注意如何使用三元运算符添加复选框:

var thirdValueComplex = $('#thirdComplex').is(':checked') ? parseFloat($('#thirdComplex').val()) : 0;
于 2015-05-21T01:04:28.963 回答