简体   繁体   中英

Count inputs number onchange

i have a little problem with my code, i need to count inputs when change the value, my code is working but when i used the increase button the count dont change the value.

HTML CODE:

<div class="input-group input-number-group">
  <div class="input-group-button">
    <span class="input-number-decrement">-</span>
  </div>
  <input class="input-number" type="number" value="1" min="0" max="1000"  onchange="count(this.value);">
  <div class="input-group-button">
    <span class="input-number-increment">+</span>
  </div>  
</div>
<div class="input-group input-number-group">
<input class="input-number" type="text" id="totalcount" placeholder="0" />
</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

JS CODE:

$('.input-number-increment').click(function() {
  var $input = $(this).parents('.input-number-group').find('.input-number');
  var val = parseInt($input.val(), 10);
  $input.val(val + 1);
});

$('.input-number-decrement').click(function() {
  var $input = $(this).parents('.input-number-group').find('.input-number');
  var val = parseInt($input.val(), 10);
  $input.val(val - 1);
})

/* Count. */
function count(value) {
    var Total = 0;  
    value = parseInt(value); // Convertir a numero entero (número).
    Total = document.getElementById('totalcount').value;
    // Valida y pone en cero "0".
    Total = (Total == null || Total == undefined || Total == "") ? 0 : Total;
    /* Variable genrando la suma. */
    Total = (parseInt(Total) + parseInt(value));
    // Escribir el resultado en una etiqueta "span".
    document.getElementById('totalcount').value = Total;
}

Here is the fiddle

I need to count when i press the + or rest when i press - button, any idea?

Thank so much.

the onchange event listener is triggered when the user changes the input by typing. Therefore .val() wont cause it to fire up.

You can easily trigger the onchange event manually by adding

$(".input-number").change();

to the desired functions in your code.

In your specific case this should do the trick:

$('.input-number-increment').click(function() {
  var $input = $(this).parents('.input-number-group').find('.input-number');
  var val = parseInt($input.val(), 10);
  $input.val(val + 1);
  $(".input-number").change();
});

$('.input-number-decrement').click(function() {
  var $input = $(this).parents('.input-number-group').find('.input-number');
  var val = parseInt($input.val(), 10);
  $(".input-number").change();
})

Now your count function will execute when the user clicks the increment and decrement buttons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM