Skip to content
Advertisement

JS doesn’t change the value of input

I’m writing cart-box that will change the quantity of products in cart. It works only if I have one box (one product) in cart, but when I have more products in cart it changes the value of the first input only.

This is my html code (earlier in the code I’ve got loop for my products):

<div class="amount">
    <a>
       <button type="button" class="minus">-</button>
    </a>
       <input class="amount-input" th:type="text" th:value="1" th:min="1"/>
    <a> 
       <button type="button" class="plus">+</button>
    </a>
</div>

And this is JS code:

$('.minus').click(function () {
    var parent = $(this).parent().parent();
    var input = parseInt(parent.find(".amount-input").val());
    var count = input - 1;

    //input['value'] = count;
    //parent.closest("input").value = count;
    document.querySelector("input").value = count;
});

$('.plus').click(function () {
    var parent = $(this).parent().parent();
    var input = parseInt(parent.find(".amount-input").val());
    var count = input + 1;

    //input['value'] = count;
    //parent.closest("input").value = count;
    document.querySelector("input").value = count;
});

I know that document.querySelector("input").value = count changes the first input only, because it’s first on the list, but input['value'] = count doesn’t change anything, parent.closest("input").value = count either.

Advertisement

Answer

Make sure you use valid HTML, otherwise results are not guaranteed.

Next let’s remove duplication and just use the one event listener for both buttons, changing the value added based on the presence of the plus class.

Finally, if you’re using jQuery, stick to using jQuery methodology. Also, you are doing nothing here with jQuery that couldn’t be done with simple, native, javascript.

//Use one event listener for both
$('.amount button').click(function () {
    //Find the nearest ancestor with class amoun
    var parent = $(this).closest(".amount");
    //Note you need to still use $ with jQuery Objecyd
    var input = $(parent).find(".amount-input");
    //Set the count based on the class of the button click
    var count = parseInt($(input).val()) + ($(this).hasClass("plus") ? 1 : -1 );
    //Set the value
    $(input).val(count);   
    
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="amount">
       <button type="button" class="minus">-</button>
       <input class="amount-input" type="text" value="1" min="1"/>
       <button type="button" class="plus">+</button>
</div>

<div class="amount">
       <button type="button" class="minus">-</button>
       <input class="amount-input" type="text" value="1" min="1"/>
       <button type="button" class="plus">+</button>
</div>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement