Sum of two input value by jquery

前端 未结 7 2170
滥情空心
滥情空心 2020-12-06 04:30

I have code :

function compute() {
    if ($(\'input[name=type]:checked\').val() != undefined) {
        var a = $(\'input[name=service_price]\').val();
             


        
7条回答
  •  清歌不尽
    2020-12-06 05:23

    Your code is correct, except you are adding (concatenating) strings, not adding integers. Just change your code into:

    function compute() {
        if ( $('input[name=type]:checked').val() != undefined ) {
            var a = parseInt($('input[name=service_price]').val());
            var b = parseInt($('input[name=modem_price]').val());
            var total = a+b;
            $('#total_price').val(a+b);
        }
    }
    

    and this should work.

    Here is some working example that updates the sum when the value when checkbox is checked (and if this is checked, the value is also updated when one of the fields is changed): jsfiddle.

提交回复
热议问题