1

I have a html table with some basic js interactions when users click an element. Something like this:

htmlfile.html ... ... position action

    <tr>
        <td>1</td>
        <td>
            <span class="switch-setting">Action</span>
        </td>
    </tr>

    <tr data-id="position-2">
        <td>2</td>
        <td>
            <span class="switch-setting">Action</span>
        </td>
    </tr>
</table>
...
...

<script src="js/settings-table.js"></script>

settings_table.js

$(function () {
    $('.switch-setting').on('click', function () {
        alert('show alert');
    });
})

In the same htmlfile is a form that sends an ajax request on submit. After the response a new element is added to the table.settings-table.

This is an example of the ajax response to add a new <tr> element to the table.

$.post(url, form.serialize(), function (response) {
    $('.settings-table').append(response);
}); 

Response is:

<tr>
    <td>3</td>
    <td>
        <span class="switch-setting">Action</span>
    </td>
</tr>

My problems is

Clicking on the span.switch-setting element of the via js added new row <tr> has no effect; the action defined in settings_table.js is not running for

What i tried

  • Adding the settings_table.js function to the response and the new element of the ajax request then clicking the new el my javascript works

  • But if an older element in the table is clicked the alert is shown two times, and,

  • if another element is added then clicking again on some older element the alert is shown three times.

Some idea how to add javascript interactions to elements added via js or to prevent these multiple calls?

surfmuggle
  • 5,527
  • 7
  • 48
  • 77
Danna Castro
  • 279
  • 1
  • 4
  • 13
  • You have to attach event handlers to the added elements see http://stackoverflow.com/questions/13767919/ – surfmuggle Jul 26 '16 at 21:12
  • why not give the new item an randomly generated ID, then select it with that ID and give it the function listener? i think that will solve your problem of the function being called multiple times – Newbie Jul 26 '16 at 21:15
  • @surfmuggle she understands that she has to rebind them, the problem is that it will add a second binding to the old elements – Newbie Jul 26 '16 at 21:21

1 Answers1

2

Try rewrite your on code:

$('.settings-table').on('click', '.switch-setting', function () {
    alert('show alert');
});