Muli Muli - 4 months ago 14
jQuery Question

remove link when checkbox is checked

I have a table with Datatable plugin, and I did the part when the user clicks on the row (

tr
) that he will be redirected to that link. but i don't want the user to be redirected to the link when he clicks the checkbox on the row.
Here is the html:

<tr class="odd gradeX">
<td class="number_elem_lang">
<label class='with-square-checkbox2-mylist-details'>
<input type='checkbox'>
<span></span>
</label>
</td>
<td class=""> ID022ox</td>
<td class="list-name">First Lipsum List</td>
<td class=""> 22 Candidates</td>
<td class="">01 Apr 2016</td>
<td><a href=""></a></td>
</tr>


Here is my javascript code for redirecting the user to the link when it's clicked:

$('#sample_1').on( 'click', 'tr', function() {
var $a = $(this).find('a').last();
if ( $a.length )
window.location = $a.attr('href');
} );


So i don't want to redirect the user when the checkbox is clicked, pls help :)

Thank you

Answer

You can use e.target to check what element the user clicked on. In the example below, we check if the user clicked on an input of type checkbox. Then we don't run the rest of the function.

$('table').on( 'click', 'tr', function(e) {
    var target = $(e.target);
    debugger; // For debugging purposes.
    if (target.is('input[type=checkbox]')) {
        // Do not continue if it's an input
        console.log('no redirect');
        return true;
    }
    console.log('do redirect');
    var $a = $(this).find('a').last();
    if ( $a.length )
       window.location = $a.attr('href');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr class="odd gradeX">
   <td class="number_elem_lang">
      <label class='with-square-checkbox2-mylist-details'>
      <input type='checkbox'>
      <span></span>
      </label>
   </td>
   <td class=""> ID022ox</td>
   <td class="list-name">First Lipsum List</td>
   <td class=""> 22 Candidates</td>
   <td class="">01 Apr 2016</td>
   <td><a href=""></a></td>
</tr>
</table>