get all the input value and make an addition

后端 未结 2 2074
走了就别回头了
走了就别回头了 2021-01-23 05:15
    
  • 相关标签:
    2条回答
    • 2021-01-23 05:53

      Try this:

      var $inputs = $('.liste_couleur_qty li input');
      $inputs.keyup(function() {
         var result = 0;
         $inputs.each(function(){
           result += parseInt(this.value, 10);
         });
         $('#qtyvalue').html(result);    
      });
      

      This would need to be in a document ready handler or in a script block after the elements in question (many people put their scripts at the end of the body).

      In your code, input.onkeyup = ... wouldn't work because there is no variable input (it doesn't automatically pick up all input elements), and also using someElement.onkeyup = only lets you attach a handler to one element at a time. Use jQuery to bind the keyup handler instead. Also, to use the total at the end just use result, using result.value wouldn't work.

      0 讨论(0)
    • 2021-01-23 06:12

      What you want is this:

      $(document).ready(function() { //wrap in a document.ready event handler
          $('input').on('keyup', function() { //bind using jQuery
              var result = 0;
              $('.liste_couleur_qty li input').each(function() {
                  result += parseInt(this.value, 10);
              });
              $('div#qtyvalue').text(result); //result.value doesn't exist, use result.
          });
      });​
      

      Here's a demo: http://jsfiddle.net/jeRdA/

      UDPATE:

      To allow for users changing the value of any of the inputs to ''(e.g., blank, or empty) or a non-numeric value, modify the line:

      result += parseInt(this.value, 10);
      

      to:

      result += parseFloat(this.value, 10) || 0;
      

      Updated fiddle: http://jsfiddle.net/jeRdA/3/

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