MAHAR MAHAR - 4 months ago 14
Javascript Question

change not working jQuery

I'm trying to show change value in a

div
but not working. Here is a example :



button_up=document.getElementById('up');
button_down=document.getElementById('down');

button_up.onclick=function() {setQuantity('up');}
button_down.onclick=function() {setQuantity('down');}

quantity = document.getElementById('quantity');

function setQuantity(upordown) {

if (quantity.value > 1) {
if (upordown == 'up'){++quantity.value;}
else if (upordown == 'down'){--quantity.value;}}
else if (quantity.value == 1) {
if (upordown == 'up'){++quantity.value;}}
else
{quantity.value=1;}

}

$('.order-option input[type=\'text\']').change(function(){
$('.show').text($('#quantity').val())
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="order-option">Quantity: <span id="quantity-field">
<button id="down">-</button>
<input type="text" id="quantity" value="1">
<button id="up">+</button>
</span>
</div>
<div class="show"></div>




Answer

Change event wont be invoked when you are trying to do with jquery, it will be triggered only when you force change the value by mouse or keyboard... So you need to trigger the change event while setting the quantity as per functionality.

var button_up=document.getElementById('up');
var button_down=document.getElementById('down');

button_up.onclick=function() {setQuantity('up');}
button_down.onclick=function() {setQuantity('down');}

var quantity = document.getElementById('quantity');
var $targetInput = $('.order-option input[type=\'text\']');
function setQuantity(upordown) {

    if (quantity.value > 1) {
        if (upordown == 'up'){++quantity.value;}
        else if (upordown == 'down'){--quantity.value;}}
    else if (quantity.value == 1) {
        if (upordown == 'up'){++quantity.value;}}
    else
        {quantity.value=1;}
   $targetInput.trigger('change');
}

$targetInput.change(function(){
    $('.show').text($('#quantity').val())   ;
  });