7

I am making a table row clickable but once clicked I want to open a new tab. I tried using data-target but that didn't work.

<tr class="table-row" data-href="mypage.php" data-target="_blank"></tr>

<script type="text/javascript">
    $(document).ready(function ($) {
        $(".table-row").click(function () {
            window.document.location = $(this).data("href");
        });
    });
</script>
freginold
  • 3,946
  • 3
  • 13
  • 28
Iggy's Pop
  • 589
  • 1
  • 6
  • 24

4 Answers4

5

could be done like this:

jQuery: JSFiddle 1

$('.table-row').each(function() {
  var $th = $(this);
  $th.on('click', function() {
    window.open($th.attr('data-href'), $th.attr('data-target'));
  });
});

Pure JS: JSFiddle 2

var tableRows = document.getElementsByClassName('table-row');

for (var i = 0, ln = tableRows.length; i < ln; i++) {
  tableRows[i].addEventListener('click', function() {
    window.open(this.getAttribute('data-href'), this.getAttribute('data-target'));
  });
}
Mi-Creativity
  • 9,554
  • 10
  • 38
  • 47
2

This should work. It will open new tab;

HTML

  <table>
        <tr class="table-row" data-href="mypage.php" data-target="_blank">
          <td>something</td>
        </tr>
    </table>

JavaScript

  $(document).ready(function ($) {
    $(".table-row").click(function () {
        window.open($(this).data("href"), $(this).data("target")); // Open new tab line
    });
});
Aiwass 418
  • 193
  • 2
  • 7
0

Have you tried:

<tr class="table-row" 
onclick="window.open('http://website-name.com/mypage.php', '_blank');">
izk
  • 234
  • 6
  • 19
Aiwass 418
  • 193
  • 2
  • 7
  • This opens a new tab as I want but the initial page then redirects to mysite.com/undefined – Iggy's Pop May 08 '17 at 18:55
  • add this: window.open('http://wbsite-name.com/mypage.php', '_blank'); after window.document.location = $(this).data("href"); - it should redirect and then open empty tab. – Aiwass 418 May 08 '17 at 18:59
  • But then I am specifying a url twice as I already have the url in the data-href? – Iggy's Pop May 08 '17 at 19:03
0

In this case you need to use windows.open and you can use _blank

<tr class="table-row" data-href="mypage.php">


$(document).ready(function ($) {
  $(".table-row").click(function () {
    var url = $(this).data("href");
    window.open(url,'_blank');
  });
});
Mils
  • 1,479
  • 3
  • 19
  • 42
  • Thank you. If I do that and click on the link it takes me to mysite.com/undefined – Iggy's Pop May 08 '17 at 18:52
  • Sorry, I see it was doing that because I had some javascript. I removed that javascript and now nothing happens at all when I click on the link. I will post the jQuery in my original question. – Iggy's Pop May 08 '17 at 18:57