2

Here is the code: http://jsfiddle.net/cwWWN/

I'm still fresh to jQuery. All I'm wanting to do is have an Add and Delete button that'll add a row when the Add is pushed and Delete the row that the button is clicked on. For some reason, the Add button stops working after the first append. If I do a clone, like the commented out code, the Add button stops working after the first Delete. Any ideas?

HTML:

<table border="1" name="phoneTable" id="phoneTable" width="100%">
<thead>
    <tr>
        <th> Primary </th>
        <th> Type </th>
        <th> Phone Number</th>
        <th> Details </th>
        <th> Add </th>
        <th> Delete </th>
    </tr>
</thead>
<tbody>
    <tr>
        <td><input type="radio" name="phonePrimary[]"/></td>
        <td>
            <select style="" name="phoneType[]">
                <option value="1">NOT COMPLETED</option>
                <option value="2">MOBILE</option>
                <option value="3">HOME</option>
                <option value="4">WORK</option>
                <option value="5">NEAR BY</option>
            </select>
        </td>
        <td><input type="text" style="width: 200px;" name="phoneNumber[]" /></td>
        <td><input type="text" name="phoneDetails[]" /></td>
        <td><button type="button" id="addButton">+ Add</button></td>
        <td><button type="button" id="deleteButton">- Delete </button></td>
    </tr>
</tbody>

JS:

$("#addButton").on("click", function () {
    alert("Clicked the add! ");
    $('#phoneTable tr:last').after('<tr><td><input type="radio" name="phonePrimary[]"/></td><td><dropdown:DropdownPhoneType entities="${applicationBean.phoneTypes}" name="phoneType[]"/></td><td><input type="text" placeholder="(999) 999-9999" class="phone-mask textfield" data-tooltip="Please enter a valid <b>Number</b>" style="width: 200px;" name="phoneNumber[]" /></td><td><input type="text" name="phoneDetails[]" /></td><td><button class="button button-black" type="button" id="addButton">+ Add</button></td><td><button class="button button-black" type="button" id="deleteButton">- Delete </button></td></tr>');
    //$('#phoneTable  tbody > tr:last').clone(true, true).appendTo("#phoneTable");
    $('#phoneTable  tbody > tr:last').prev().find("button[id='addButton']").remove();                                    
});

$("#deleteButton").on("click", function () {
    if($("#phoneTable tbody > tr").length <= 1) {

        return false;
    }
    $('#phoneTable tbody > tr:nth-last-child(2) > td:nth-last-child(2)').append('<button type="button" id="addButton">+ Add</button>');
    $
    $('#phoneTable tbody > tr:last').fadeOut('slow', function () {
        $('#phoneTable tbody > tr:last').remove();
    });
    //alert('Delete Clicked');
});
user2195836
  • 45
  • 1
  • 1
  • 5
  • possible duplicate of [Jquery doesn't work after ajax loads](http://stackoverflow.com/questions/16062899/jquery-doesnt-work-after-ajax-loads) – Anthony Grist May 02 '13 at 15:44
  • To preempt any complaints that they're not duplicates, my answer on that question addresses all of the relevant points to solve this issue. It mentions AJAX because the question was about DOM changes after an AJAX request, but it applies equally to any changes made via JavaScript even if there wasn't an AJAX call involved. Also, ignore the latter part about plugins, since that's not relevant here. – Anthony Grist May 02 '13 at 15:46
  • Wow! News to me. Huh. There was a quick post that got deleted that said: `$("#phoneTable").on("click", "#addButton",` Which in this case, did reconnect the communication. Though, that AJAX/jQuery stuff may throw a wrench in. I'll be talking to my coworker about that and see what we come up with. Thank you. – user2195836 May 02 '13 at 15:51
  • Yeah, it also got downvoted for reasons I don't understand; it was a bit light on details but it was technically correct. The poster has deleted it, though they may choose to undelete it. – Anthony Grist May 02 '13 at 15:51

3 Answers3

14

.on() doesn't work like you think it does. If you want the event to be delegated (in old terms, live), you need to bind the event to a parent, and pass it an optional selector parameter. So for any elements that are added dynamically after the hander is initially bound, you need to bind your events like so:

$('body').on('click', '#addButton', function() {
   // code here
});

See: http://api.jquery.com/on/

Christian
  • 19,605
  • 3
  • 54
  • 70
  • This method did work after testing it. So did `$("#phoneTable").on("click", "#addButton" function() { // code here });` – user2195836 May 02 '13 at 15:56
  • the '.on()' method is not only about delegating. Your example will trigger an event anytime the user is clicking the body and then the on method is going to check if the user clicked the button. Time and resource consuming !! For info, the way he wrote his '.on()' method can be shortcutted with '.click()' method. He has probably learned this '.on()' method from the codeSchool jQuery course. – pdegand59 May 02 '13 at 16:02
  • @pdegand59 Yeah, It's better to bind the event to the nearest parent, not the body. However he _does_ need to use `.on()`, as per his example his elements are being generated dynamically, and thus require a delegated handler. – Christian May 02 '13 at 16:12
1

Try this - working demo -- > http://jsfiddle.net/mohammadAdil/cwWWN/4/

$("#phoneTable").on("click","#deleteButton", function () {

$("#phoneTable").on('click', '#addButton', function() {
Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
1

The reason why your new ADD button is not working is that you don't add the click event listener when you are creating your new ADD button.

Fiddle example

From the Fiddle:

function addRow() {
    alert("Clicked the add! ");
    $('#phoneTable tr:last').after('<tr><td><input type="radio" name="phonePrimary[]"/></td><td><dropdown:DropdownPhoneType entities="${applicationBean.phoneTypes}" name="phoneType[]"/></td><td><input type="text" placeholder="(999) 999-9999" class="phone-mask textfield" data-tooltip="Please enter a valid <b>Number</b>" style="width: 200px;" name="phoneNumber[]" /></td><td><input type="text" name="phoneDetails[]" /></td><td><button class="button button-black" type="button" id="addButton">+ Add</button></td><td><button class="button button-black" type="button" id="deleteButton">- Delete </button></td></tr>');
    //$('#phoneTable  tbody > tr:last').clone(true, true).appendTo("#phoneTable");
    $('#phoneTable  tbody > tr:last').prev().find("button[id='addButton']").remove();
    $("#addButton").on("click", addRow);
}

$("#addButton").on("click", addRow);

Just do the same thing for the remove Button.

pdegand59
  • 12,776
  • 8
  • 51
  • 58