Question

I have a shopping cart that calculates cost and shipping based on quantity and weight. Because of this there are two possible shipping options and I have a function to auto-select the correct shipping on page load. However, if a person changes the quantity the function to select the shipping must run again.

To do this I tried this code:

$('.cartInputText').on('change', function() {   
    $('#ShippingOptions option').each(function(){
        if (this.value == '163182') {
            $('#ShippingOptions option[value="163182"]').prop('selected', true)
            return false;
        }
        if (this.value == '163183') {
            $('#ShippingOptions option[value="163183"]').prop('selected', true)
            return false;
        }
    });
});

This works the first time I change the quantity. If I change the quantity a second time it doesn't work. How do I fix this so no matter how many times I change the quantity it works?

Update

The onchange event fires the first time but does not fire the second time. Why?

Was it helpful?

Solution

Please use live instead of on, or if the version of jQUery is higher than 1.9, please make you code like this: $(document).on('change','.cartInputText',function(){});

For your sample code, you only bind the function to .cartInputText, if the page re-renders or whatever the reason cause .cartInputText re-generate, it loses the function.

For my code, I bind the function to document and I think you know the event of html element can bubble, you click on .cartInputText and it bubbles up to document and let the function be triggered. More, please check Live and Bind difference in jQuery.

OTHER TIPS

User KeyUp function instead of change for detecting input text.

Like:

$('.cartInputText').keyup(function () {
    alert('test');
});

Here's the official jQuery documentation for .keyup().

DEMO

the above code works for the html code which is added before executing the previous statements,

if some other content with the same class (cartInputText) is added dynamically you need to assign above functionality by calling it again after adding the content.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top