Search code examples
jquerytriggers

trigger click on mouse find previous i element


I have a page where i use an i element to add a row to form:

jquery:

 $('body').on('click','.newTask',function(){
    var id= $(this).attr('data-tableId');
   //ajax call to get 
        <tr>
          <td><input type='text'></td>
          <td><input type='text'></td>
          <td><input type='text' class='last'></td>
        </tr>
    success:function(result){
         $('#newTableRow_'+id).append(result);
   //
 }); 

the tables:

<table id='1'>
  <tr>
     <td><i class="bi bi-plus-circle-fill fa-1x icon-green newTask" data-tableId='1'>Add Task</i></td>
  </tr>
  <tbody id='newTableRow_1'></tbody>
</table>

<table id='2'>
  <tr>
     <td><i class="bi bi-plus-circle-fill fa-1x icon-green newTask" data-tableId='2'>Add Task</i></td>
  </tr>
  <tbody id='newTableRow_2'></tbody>
</table>

in which when this is clicked, newTask adds a new row of elements to the form.

<tr>
    <td><input type='text'></td>
    <td><input type='text'></td>
    <td><input type='text' class='last'></td>
</tr>

when the user tabs out of the element with class "last", i am trying to trigger the newTask click so a new row will be automatically added and user doesnt have to click the i. the below code fires, (the alert shows when i focusout), but the trigger.click is not happening.

    $('body').on('focusout','.last',function(){
        alert('clicked');
        $(this).closest('.newTask').trigger('click');

         //I have also tried 
            $(this).find('.newTask').trigger('click');
    });

*note - there could be many tables on this page that have the .newTask cell.


Solution

  • The easiest way to achieve this is adding an ID to <i> element and trigger click on element selected by id.

    $('body').on('focusout', '.last', function() {
      alert('clicked');
      $('#add-task-button').find('.newTask').trigger('click');
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table>
      <tr>
        <td><i id="add-task-button" class="bi bi-plus-circle-fill fa-1x icon-green newTask">Add Task</i></td>
      </tr>
      <tr>
        <td><input type='text'></td>
        <td><input type='text'></td>
        <td><input type='text' class='last'></td>
      </tr>
    </table>