Search code examples
jquerycellsremovechild

how to remove some elements of table cells using JQuery


have such a part of a markup:

<tr>
  <td class='a'>data1</td>
  <td class='a'>data2</td>
  <td class='a'>data3</td>
</tr>

there are inputs which append dynamically into 3 cells with a class like this:

$("selector").has("selector").find(".a").append("<input 
type='text'/>");

so inputs draw up one under another which build three columns from inputs.

for example we have three rows of inputs

the task is how to remove any row(it's not a table row)?
any ideas?


Solution

  • One way you could do this would be to add another column with buttons lining up with the input "rows". When you click a button, get it's index in that column then find the inputs that are also at that index in each of the columns in the row, then remove the found inputs and the clicked button.

    Something like this:

    for (var i = 0; i < 5; i++) {
     $("table").has("tr").find(".a").append('<input type="text"/>'); 
     $("table").has("tr").find(".b").append('<button>X</button>'); 
    }
    
    $(document).on('click', '.b button', function(){
       var $clickedButton = $(this);
       var $buttons = $clickedButton.parent().find('button');
       var $tableRow = $clickedButton.closest('tr');   
       var curIndex = $buttons.index($clickedButton);  
       $tableRow.find('td').find('input:eq('+curIndex+')').remove();
       $clickedButton.remove();
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <table>
      <tr>
        <td class='a'></td>
        <td class='a'></td>
        <td class='a'></td>
        <td class='b'></td>
      </tr>
    </table>