Danna Castro Danna Castro - 4 months ago 18
HTML Question

Append html and js code using javascript

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?

Answer

Try rewrite your on code:

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