Imran Imran - 7 months ago 18
HTML Question

Making clickable rows with jQuery and excluding child elements

I have a table with rows that I would like to be clickable, however there is also a button in one of my columns which when pressed should do an alternative actions.

HTML:

<table>
<tr data-url="link.html">
<td>Some Text Value <input type="button" value="Submit" onclick="otherFunction()"></td>
</tr>
<tr data-url="link2.html">
<td>Some Text Value <input type="button" value="Submit" onclick="otherFunction()"></td>
</tr>
<tr data-url="link3.html">
<td>Some Text Value <input type="button" value="Submit" onclick="otherFunction()"></td>
</tr>
</table>


jQuery:

$(document).ready(function() {
$('table tr:not(input)').click(function() {
var href = $(this).attr("data-url");
if(href) {
//console.log('redirect to:' + href);
window.location = href;
}
});
});


Currently when I click on the button the page is still redirect despite the jQuery selector excluding any inputs. Am I using the
:not
incorrectly?

Answer

You can check in the click handler whether the button was clicked by checking the event.target property

$(document).ready(function() {
  $('table tr').click(function(e) {
    if ($(e.target).is(':button')) {
      snippet.log('button clicked')
      return;
    }

    snippet.log('row clicked');
    var href = $(this).attr("data-url");
    if (href) {
      //console.log('redirect to:' + href);
      window.location = href;
    }
  });
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr data-url="link.html">
    <td>Some Text Value
      <input type="button" value="Submit" onclick="otherFunction()">
    </td>
  </tr>
  <tr data-url="link2.html">
    <td>Some Text Value
      <input type="button" value="Submit" onclick="otherFunction()">
    </td>
  </tr>
  <tr data-url="link3.html">
    <td>Some Text Value
      <input type="button" value="Submit" onclick="otherFunction()">
    </td>
  </tr>
</table>

Comments