Sum of two input value by jquery

前端 未结 7 2130
滥情空心
滥情空心 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:06

    Cast them to a Number

    $('#total_price').val(Number(a)+Number(b));
    

    But before you do that

    if (!isNaN($('input[name=service_price]').val()) {...
    
    0 讨论(0)
  • 2020-12-06 05:11

    <script>
    $(document).ready(function(){
    var a =parseInt($("#a").val());
    var b =parseInt($("#b").val());
    $("#submit").on("click",function(){
    var sum = a + b;
    alert(sum);
    });
    });
    </script>

    0 讨论(0)
  • 2020-12-06 05:13

    use parseInt

       var total = parseInt(a) + parseInt(b);
    
    
        $('#total_price').val(total);
    
    0 讨论(0)
  • 2020-12-06 05:13

    if in multiple class you want to change additional operation in perticular class that show in below example

    $('.like').click(function(){    
    var like= $(this).text();
    $(this).text(+like + +1);
    });
    
    0 讨论(0)
  • 2020-12-06 05:20

    Because at least one value is a string the + operator is being interpreted as a string concatenation operator. The simplest fix for this is to indicate that you intend for the values to be interpreted as numbers.

    var total = +a + +b;
    

    and

    $('#total_price').val(+a + +b);
    

    Or, better, just pull them out as numbers to begin with:

    var a = +$('input[name=service_price]').val();
    var b = +$('input[name=modem_price]').val();
    var total = a+b;
    $('#total_price').val(a+b);
    

    See Mozilla's Unary + documentation.

    Note that this is only a good idea if you know the value is going to be a number anyway. If this is user input you must be more careful and probably want to use parseInt and other validation as other answers suggest.

    0 讨论(0)
  • 2020-12-06 05:21

    use parseInt as a = parseInt($('input[name=service_price]').val())

    0 讨论(0)
提交回复
热议问题