Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change value of two input fields to the same value, regardless of which field is used

I have two fields on my product's page, using the class '.qty'. What I want to achieve is that when I enter a value in either of the input fields, both of these input fields are filled with that value.

My current code is this:

function updateProductAmount() {
    jQuery('.add-to-cart .qty').each(function() {
        var productAmount = this.value;
        jQuery('.add-to-cart .qty').val(productAmount);
        // Requires more work.
    });
}

I'm calling this code with an onchange inside the input text elements.

This code, however only works one way. When the first input element is changed, it copies the value to the last input element. However, when the last input element is changed, it changes back to the value of the first input element.

Can anyone point out to me what I'm doing wrong and help me out?

Thanks in advance.

like image 280
Daan van den Bergh Avatar asked Jan 24 '26 06:01

Daan van den Bergh


2 Answers

Try the following:

 $(document).on('change','.add-to-cart .qty', function(){
    $('.add-to-cart .qty').val($(this).val());
 });

Js Fiddle Example

like image 92
Think Different Avatar answered Jan 26 '26 18:01

Think Different


Try passing the used inputfield as parameter. ex: to check which field was used. You could also pass a reference to 2nd field (if it is intended that you stick to two fields. Something along the lines should do the trick

<input type="text" value="" name="qty" class="qty" onchange="updateProductAmount(this, jQuery('.add-to-cart'))"/>
<input type="text" value="" name="add-to-cart" class="add-to-cart" onchange="updateProductAmount(this, jQuery('.qty'))"/>

and on the script-part

function updateProductAmount(caller, fieldToChange) {
    jQuery(fieldToChange).val(caller.value);
}
like image 44
Christopher Dittrich Avatar answered Jan 26 '26 18:01

Christopher Dittrich