One jQuery Change Event on Multiple Elements

前端 未结 6 1354
醉酒成梦
醉酒成梦 2021-01-11 13:46

I have 3 textboxes, all with the same id\'s that I process into ASP by bringing it into a controller array

I have a link that adds an unlimited number of textboxes b

6条回答
  •  离开以前
    2021-01-11 14:10

    Best strategy (95% of the time): use a class to add a listener for multiple elements. ID's are expected to be unique. Classes are made for this and will give you the most extensibility in the future.

    HTML:

    
    
    

    jQuery:

    $('.invent').change(function () {
       // Do magical things
    });
    

    For the other 5%:

    If you'd rather use unique IDs or unique field names instead of a single class as described in the selected answer, you can add a listener for multiple uniquely named elements like so:

    HTML:

    
    
    
    

    you can use jQuery multiple selectors:

    $('#invent1, #invent2, #invent3').change(function () {
       // Do magical things
    });
    

    OR you can use jQuery starts with attribute selector:

    //target based on what input id starts with
    $('[id^="invent"]').change(function () {
       // Do magical things
    });
    
    // OR target based on input name attribute starts with
    $('input[name^="something"]').change(function () {
       // Do magical things
    });
    

提交回复
热议问题