had_hc
had_hc

Reputation: 23

jquery - Add field dynamically not functioning fully

based on tutorial from here ,I'm trying to make some fields which can dynamically be added by a button an removed by another button. It almost works fine except that another group of fields that supposed to be created dynamically as well is not adding anything.

Here's what i did at codepen.

    <div class="field_wrapper">    
            <a href="javascript:void(0);" class="add_button" title="Add field">New Group</a>  
    </div>

    <script>
        $(document).ready(function(){
    var maxField = 10; //Input fields increment limitation
    var addButton = $('.add_button'); //Add button selector
    var wrapper = $('.field_wrapper'); //Input field wrapper
    var fieldHTML = '<div><a href="javascript:void(0);" class="remove_button" title="Remove field">X</a><table id="add_on_table"><tbody><tr><td><label class="field">Group Name</label><input type="text" name="product_addon_name[]"></td><td><input type="checkbox" name="product_addon_required[]"> Mark as Required</td></tr><tr><td><label class="field">Group Description </label><textarea name="product_addon_description[]"></textarea></td></tr><tr><table><thead><tr><td>Option Label</td><td>Option Price (RM) </td></tr></thead><tbody class="addonoption"><tr><td><input type="text" name="product_addon_option_label[]"></td><td><input type="text" name="product_addon_option_price[]"></td><td><a href="javascript:void(0);" class="remove_row" title="Remove field">X</a></td></tr> </tbody><tfoot><tr><td><input type="button" class="add_option" value="New Option"></td></tr></tfoot></table></tr></tbody></table></div>'; //New input field html 
    var AddRow = $('.add_option'); //Add button selector
    var RowWrapper = $('.addonoption'); //Input field wrapper
    var rowHTML = '<tr> <td><input type="text" name="product_addon_option_label[]"></td><td><input type="text" name="product_addon_option_price[]"></td><td><a href="javascript:void(0);" class="remove_row" title="Remove field">X</a></td></tr>';    
    var x = 1; //Initial field counter is 1   
    $(AddRow).click(function(){ //Once add button is clicked     
      $(RowWrapper).append(rowHTML); // Add field html           
    });
    $(addButton).click(function(){ //Once add button is clicked
        if(x < maxField){ //Check maximum number of input fields
            x++; //Increment field counter
          $(wrapper).append(fieldHTML); // Add field html
        }
    }); 
    $(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
        e.preventDefault();
        $(this).parent('div').remove(); //Remove field html
        x--; //Decrement field counter
    });
    });</script>

In reference to what I did in the linked codepen, the fields generated OK when pressed the 'New Group' link. However, the button 'New Option' does not create anything once clicked. You can see in the JS section i write some code to create field, but it's just not working. Any idea why? Btw, i'm quite noob at javascript/jquery, so, sorry if it's just a stupid mistake. Thanks in advance!

Upvotes: 2

Views: 71

Answers (2)

Lajos Arpad
Lajos Arpad

Reputation: 76436

The problem is that when you try to add a click handler to AddRow, your button does not exist yet. Instead of creating a handler to AddRow, you need to use the .on() function. Example:

$(".field_wrapper").on("click", ".add_option", function() {alert("foo");});

Explanation:

  • .field_wrapper as a selector already exists when you call on
  • click is the event you intend to handle
  • .add_option is a selector which will apply to existent and not yet existent elements inside .field_wrapper that match .add_option
  • the function is the event handler to be executed

Upvotes: 1

mhodges
mhodges

Reputation: 11116

You need to use event delegation with the .add_option elements too. Since they are created after the DOM is initially rendered, your click handler does not attach to anything. You use event delegation for the .remove_button, so you can copy that syntax to make it work:

$(document).on("click", ".add_option", function(){ //Once add button is clicked  
    $(this).closest("table").find(".addonoption").append(rowHTML);         
});

Also, I noticed that your selector is potentially messed up too because if you have multiple groups, it will add the html to each one of them. If this is the intended behavior, you can change the selector to $(".addonoption").append(rowHTML), otherwise, the above code will work for you!

Upvotes: 2

Related Questions