简体   繁体   中英

Delete button in table, jQuery

I wrote the code, using JS and jQuery. The code adds new rows to my table. Every row contains the delete button and it do not work. I'm going to implement also edit button.

My table:

<div class="row">
   <div class="col-md-12">
      <table class="table table-striped" id = "my-table">
       <thead>
        <tr>
            <th>Date</th>
            <th>Example</th>

        </tr>
          </thead>
          <tbody>



          </tbody>

        </table>

   </div>
   </div>
  </div>

JS code:

$(document).ready(function(){
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
} 

if(mm<10) {
mm='0'+mm
} 
today = mm+'/'+dd+'/'+yyyy;
//var counter = 1;


$('button#sending_button').click(function(){
    var text = $('textarea#mytextarea').val();
    $('#my-table').append('<tr><td>'+today+'</td><td>'+text+'</td><td><button type="button" id="delete-button"  class="btn btn-danger">Usuń</button></td></tr>');
    $('textarea#mytextarea').val('');
    //counter++;

});

$('#my-table').on('click', 'button.btn btn-danger', function() {
    $(this).parents('tr').remove();  

});

});

I don't know what more I should explain about this problem.

Your problem is here:

$('#my-table').on('click', 'button.btn btn-danger', function() {

It should be button.btn.btn-danger .

Some random suggestions:

  • Don't repeat the id of each button (" delete-button "): id's should be unique
  • Use a semantically meaningful class instead ( delete button would also be good)
  • Use said class when defining the delegate event listener, instead of button.btn.btn-danger (which is too bound to the DOM and its style definition)
  • Use parent instead of parents to avoid surprises. They're two different methods with different goals
  • Event better, use closest .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM