JQuery event handling on dynamically added elements

I have an RMA form in which I can add fields dynamically, but I have problems with event handling (e.g. click, change).

I am adding fields with .appendTo("#container");and increasing the NAME parameter with a counter, so that when the user clicks "Submit" I will get "Category1: blah" "Category2: blah blah" "Category 3: something_else ', etc.

The problem is that I add more fields (for example, a drop-down list) dynamically, events do not follow. I have 3 drop downs [category] [subcategory] [model]. When I choose a category:

jQuery('#cat').bind("change", function()
    {
        jQuery('#subcat').empty();
        jQuery('#subcat').attr('disabled', 'disabled');
        jQuery('#model').empty();
        jQuery('#model').attr('disabled', 'disabled');

        LoadSeries(jQuery(this).val()); // I do a .removeAttr('disabled'); in here for #subcat

    });

jQuery('#cat'+counter).bind("change", function() { ..., , , [] .

.live, , / (cat2, cat3, cat4, cat5...)

? (LoadSeries2, LoadSeries3 ..) ?

.

EDIT: HTML- [category] [subcategory] [model]. , , .

    newTextBoxDiv.after().html('
    <div class="item'+counter+'"><br/>
    <table width="820" border=1 cellspacing="0" cellpadding="0" align="center" style="border: 1px; border-color: #000;">
      <tr>
         <td>
            <div align="center" style="font-size: 14px;">
            <input type="radio" class="radioBtn'+counter+'" name="Return_Exchange'+counter+'" value="Return" selected="selected">Return
            <input type="radio" class="radioBtn'+counter+'" name="Return_Exchange'+counter+'" value="Exchange">Exchange</div>
...
+3
3

live() delegate() . (^=), ...

$("#container").delegate("[id^='cat']", "change", function() {
    $("#subcat, #model").empty().attr("disabled", true);
    LoadSeries($(this).val());
});

jQuery on

$("#container").on("change", "[id^='cat']", function() {
    $("#subcat, #model").empty().attr("disabled", true);
    LoadSeries($(this).val());
});
+2

, ..

<input class="cat3 eventClass" />

.live() $('.eventClass')

0

You can use the starts with the selector together with the live Try the following:

jQuery('[id^=cat]').live("change", function ()
{
    var $this = $(this);
    var id = this.id.replace(/[^0-9]/, "");
    jQuery('#subcat' + id).empty();
    jQuery('#subcat' + id).attr('disabled', 'disabled');
    jQuery('#model' + id).empty();
    jQuery('#model' + id).attr('disabled', 'disabled');
    LoadSeries(jQuery(this).val()); // I do a .removeAttr('disabled'); in here for #subcat      
});
0
source

Source: https://habr.com/ru/post/1783705/


All Articles