Javascript - returning concatenates instead of sum of variables from input

前端 未结 6 871
南笙
南笙 2021-01-23 07:12

I am trying to get values from input field using .each() and adding them to show the sum in another input value. But unfortunately in spite of using parseInt() I am

相关标签:
6条回答
  • 2021-01-23 07:56

    your appending String. $(this).val() is a string . just parse it to int or float.

    0 讨论(0)
  • 2021-01-23 08:03

    Try with parseFloat() on input value

    parseFloat($(this).val()));
    

    var totalvalue = parseInt(0);
    $(document).on("focusout",".value",function() {
        $(".value").each(function() {
            totalvalue = (totalvalue + parseFloat($(this).val()));
        });
        $("#totalvalue").val(totalvalue);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type=text name=value[] id=value class="value">
    <input type=text name=totalvalue id=totalvalue>

    0 讨论(0)
  • 2021-01-23 08:05

    You should declare totalvalue inside focusout function ,because it will always show the total of two input text and pass the input value empty state when sum !!!

    $(document).on("focusout",".value",function() {
        var totalvalue = 0;
        $(".value").each(function() {
            if($(this).val() == "") return;
            totalvalue +=  parseInt($(this).val());
        });
        $("#totalvalue").val(totalvalue);
    });
    
    0 讨论(0)
  • 2021-01-23 08:05

    You are adding a NaN data type to an Number data type. So you need to restrict it before you perform your addition operation.

    Please check this one

    var totalvalue = 0;
    $(document).on("focusout",".value",function() {
        $(".value").each(function() {
            if(isNaN($(this).val()) || $(this).val() != ''){
                totalvalue = totalvalue + parseInt($(this).val());
          }
      });
      $("#totalvalue").val(totalvalue);
    
    });
    
    0 讨论(0)
  • 2021-01-23 08:15

    What you're parsing line is saying is

    Add the totalValue to the string from the input, then parse the result.

    Which is why it's concatenating. Instead, you need to add the totalValue outside of the parseInt() so that it's saying

    Take the take the totalValue and add the parsed input value to it.

    Like this

    totalvalue = totalvalue + parseInt($(this).val());
    

    This can be further shortened to

    totalvalue += parseInt($(this).val());
    
    0 讨论(0)
  • 2021-01-23 08:16

    If your purpose is this according to your code then it will always sum up with first box value.

      var value = parseInt($(this).val());
        if(value)
        totalvalue = totalvalue + value;
    });
    

    Otherwise you should elaborate your question so that proper answer could be provided.

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