I ask for help, the task is to add all that in value with the class num. Problems arise if value is '-' or 'empty' instead of a number, then sum takes an empty value. How to make a conversion, so that if an invalid character is in value or a negative number, then they are converted to zero?

<table> <tr> <td> <input type='text' class='num' name='num1' value='2'> </td> <td> <input type='text' class='num' name='num1' value='3'> </td> <td> <input type='text' class='num' name='num1' value='-'> </td> </tr> 


  var sum = 0; $('.num').each(function(){ sum += parseInt($(this).val()); }); console.log(sum); 

    3 answers 3

    You can use the logical operation OR . Which returns the first operand, which is cast to true.

    in this case, as a result of calling parseInt , on failure, NaN will be returned, which is held to false .

    Therefore, you can use the following entry:

      var sum = 0; $('.num').each(function(){ sum += parseInt($(this).val()) || 0; // если не число - прибавляем 0 }); console.log(sum); 

    Example:

     var sum = 0; $('.num').each(function() { sum += parseInt($(this).val()) || 0; }); console.log(sum); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td> <input type='text' class='num' name='num1' value='2'> </td> <td> <input type='text' class='num' name='num1' value='3'> </td> <td> <input type='text' class='num' name='num1' value='-'> </td> </tr> 

       $('.num').each(function(){ var value = parseInt($(this).val()); if (!isNaN($(this).val()) && value > 0) sum += value; }); 

        Split into two operations

         // побитовое "или" вернет цифру если она есть, в любом другом случае ноль var a = $this.val() | 0; // Проверка на отрицательное значение sum += a < 1 ? 0 : a;