7

Jquery adds a click event after adding a new row in the table WITHOUT function

 2 years ago
source link: https://www.codesd.com/item/jquery-adds-a-click-event-after-adding-a-new-row-in-the-table-without-function.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Jquery adds a click event after adding a new row in the table WITHOUT function

advertisements

That's my problem, I append a new row in my table. In this row is a button, that should be clickable and fire an event. I found tons of solutions, but each of them contains this way:

.on('click', 'button', function(){
//do something
});

In need a solution without that function-call on this place (only activate the click possibility). The reasen is, I have three different ajax parts for add, edit and delete a table row. I control this by a contentEditable table. So each row gets a button to edit and delete this row. If I insert a new line, the new row will get these buttons. To make my button run like the example above, I get a structure like this :

// AJAX for edit row
do something

// AJAX for delete row
do something

// AJAX for add row
$('#editTable > tbody:last').append('<tr><td><button>DELETE</button></tr><td>');

$('#table').on('click', 'button', function() {
    // AJAX for delete row
    do something
});

By this way, I see the problem,I have to write the complete AJAX-delete part twice.

Theoretical it sounds soooo easy, activate the click event for the delete button and after click it, the AJAX delete part will be called.

But in pratice I found a easy solution like this.

Hope you guys have one for me...

Thanks a lot!!!


Give your added buttons a global class e.g delete and use event delegation on() to add one event for all the buttons, check example bellow.

JS :

$('#editTable > tbody:last').append('<tr><td><button class="delete">DELETE</button></tr><td>');

$('body').on('click', '.delete', function (event) {
    //Your code here
});

Hope this helps.


$('body').on('click', '#add', function (event) {
  $('#editTable').append('<tr><td>test<td><td><button class="delete">DELETE</button></tr><td>');
});

$('body').on('click', '.delete', function (event) {
    alert("AJAX for delete row");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add">Add row</button>
<table id="editTable">
    <thead>
      <th>TEST</th>
      <th>Action</th>
    </thead>
</table>

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK