Home > front end >  Jquery nested onclick method
Jquery nested onclick method

Time:05-19

I have onclick method in table tag.I also have it in my tag. I'm just trying to cancel the click method on when the delete button in is pressed.

  @foreach (var item in Model.PickupTemplate.PickupBags.OrderByDescending(x => x.Id))
                            {
                                <tr id="[email protected]" onclick="RedirectToBagDetailsPage(@item.Id)" style="cursor:pointer;" >
                                    <td>@item.BagName - @item.BagOrderId</td>
                                    <td>@item.TotalBillOfLadingWeightPhysical</td>
                                    <td>@item.TotalBillOfLadingWeight</td>
                                    <td>@item.TotalBillOfLadingCount</td>
                                    <td><a onclick="DeletePickupBag(@item.Id)"><i ></i></a></td>
                                </tr>
                            }

How can i do it using jquery or javascript?

CodePudding user response:

You need to stop the inner click event on the a element from propagating up the DOM to the tr for it to be caught there too.

To do this, and also to improve the quality of your code, use unobtrusive event handlers which are assigned in JS code, not in your HTML. From there you can access the event as an argument to the event handler and call stopPropagation() on it.

As you've tagged the question with jQuery, here's how to do it:

$('.bagList').on('click', e => {
  let itemId = $(e.currentTarget).data('item-id');
  
  // redirect logic here...
  console.log('Redirect', itemId);  
});

$('.bagList a').on('click', e => {
  e.stopPropagation();
  e.preventDefault();
  let itemId = $(e.target).closest('.bagList').data('item-id');
  
  // delete logic here...
  console.log('Delete', itemId);
});
  
.bagList { 
  cursor: pointer;
} 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table>
  @foreach (var item in Model.PickupTemplate.PickupBags.OrderByDescending(x => x.Id)) 
  {
    <tr id="[email protected]" data-item-id="@item.Id" >
      <td>@item.BagName - @item.BagOrderId</td>
      <td>@item.TotalBillOfLadingWeightPhysical</td>
      <td>@item.TotalBillOfLadingWeight</td>
      <td>@item.TotalBillOfLadingCount</td>
      <td><a href="#"><i ></i>Delete</a></td>
    </tr>
  }
</table>

Here's the same logic in plain JS:

document.querySelectorAll('.bagList').forEach(bagList => {
  bagList.addEventListener('click', e => {
    let itemId = e.currentTarget.dataset['item-id'];

    // redirect logic here...
    console.log('Redirect', itemId);
  })
});

document.querySelectorAll('.bagList a').foreach(a => {
  a.addEventListener('click', e => {
    e.stopPropagation();
    e.preventDefault();
    let itemId = $(e.target).closest('.bagList').data('item-id');

    // delete logic here...
    console.log('Delete', itemId);
  });
});
  • Related