Balaji Chandrasekaran
Balaji Chandrasekaran

Reputation: 512

jQuery onchange not working for multiple element with same class

I am adding multiple text box element with the same class.

It's not working in my project, for demo purpose i added the code to (http://jsfiddle.net/8gbvd/)

Its working there how to debug this issue

Thank you

Upvotes: 1

Views: 4933

Answers (2)

Invincible
Invincible

Reputation: 1460

If you have same class for multiple select elements and you want to get selected value, only for the changed element, then you can do something as below:

$('#priceRuleTable').on('change', '.qtyBox', function(){
    //to check only selected item is being triggered add css, you can remove it later
    $(this).parent().css("border", "2px solid red");
    //you should get value of the changed select element 
    var v = $(this).parent().find("option:selected").text();
    console.log(v);
});

Upvotes: 0

Laurent S.
Laurent S.

Reputation: 6947

As your textboxes are dynamically added to the page, you need to use delegated events. So

DON'T DO THIS :

jQuery('.qtyBox').change(
    function(){
         alert(jQuery(this).val());
    });

BUT DO THIS INSTEAD :

jQuery('#priceRuleTable').on('change','.qtyBox',
    function(){ 
        alert(jQuery(this).val());
    });

cfr this page for a more detailed explanation on event delegation.

note that if you want to perform an action each time a key is pressed (and not when the user leaves the textbox , you can use the event input instead of change

Upvotes: 4

Related Questions