/    Sign up×
Community /Pin to ProfileBookmark

Double click on a table row

I just want to double click on a table row, fetch id and redirect to another page.
http://jsfiddle.net/fdwcob7x/
All examples I have seen are using JQuery, but how do I do this using Vanilla?

to post a comment
JavaScript

11 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumApr 14.2020 — getElementsByTagName returns a node list, something like an array. You need to code a loop and add the eventlistener to each element in the list. This is different from jQuery which does it automatically.
Copy linkTweet thisAlerts:
@cootheadApr 14.2020 — Hi there @sibert,

here is an example, which employs @Sempervivum's suggestion...

``<i>
</i>&lt;!DOCTYPE HTML&gt;
&lt;html lang="en"&gt;
&lt;head&gt;

&lt;meta charset="utf-8"&gt;
&lt;meta name="viewport" content="width=device-width,height=device-height,initial-scale=1"&gt;

&lt;title&gt;getElementsByTagName example&lt;/title&gt;

&lt;!--&lt;link rel="stylesheet" href="screen.css" media="screen"&gt;--&gt;

&lt;style media="screen"&gt;
h1 {
font-size:1.25em;
}

tr {
cursor: pointer;
}
&lt;/style&gt;

&lt;/head&gt;
&lt;body&gt;

&lt;h1&gt;getElementsByTagName example&lt;/h1&gt;

&lt;table id="table"&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;BMW&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;VW&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;Mercedes&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;

&lt;script&gt;
( function( w, d ) {

var c, row = d.getElementsByTagName( 'tr' ),
urls = [ 'https://www.bmw.com',
'https://www.vw.com',
'https://www.mercedes-benz.com'
];

for ( c = 0; c &lt; row.length; c ++ ) {
row[ c ].addEventListener( 'dbclick', goto( c ), false );
}

function goto( c ) {
row[ c ].ondblclick = function() {
w.location = urls[ c ];
}
}

} ( window, document ) );
&lt;/script&gt;


&lt;/body&gt;
&lt;/html&gt;<i>
</i>
``


_coothead_
Copy linkTweet thisAlerts:
@sibertauthorApr 14.2020 — > @coothead#1617406 here is an example

Thank you! Basically exact what I was looking for. But I have a dream to understand what I am doing as well.

Therefore I have modified your code so it no longer works :-)

https://jsfiddle.net/o12cm6f8/9/

  • 1. How can I replace the iteration with forEach? (easier for me to understand)

  • 2. How can I fetch some row id (like /topics?10 in order to lookup number 10)?

  • 3. Why do I need to trap double click twice?
  • Copy linkTweet thisAlerts:
    @cootheadApr 14.2020 — Hi there sibert.

    >[color=navy]**ForEach**

    forEach is an Array method that we can use to execute

    a function on each element in an array.

    [size=18]**It can only be used on Arrays, Maps, and Sets**[/size].[/color]


    **Source:-**

    [url=https://codeburst.io/javascript-the-difference-between-foreach-and-for-in-992db038e4c2#893f][color=navy][u]Javascript - forEach()[/u][/color][/url]

    _coothead_
    Copy linkTweet thisAlerts:
    @KeverApr 14.2020 — There is no need to trap doubleclick twice. The code Coothead posted misses an 'l' in dbclick', so it doesn't listen for an event. Because of the parentheses on goto(c), the function goto() is executed which attaches a handler to ondblclick. The function goto() was probably meant to be a closure to capture the state of the variable 'c'.
    <i>
    </i>( function( w, d ) {

    var c, row = d.getElementsByTagName( 'tr' ),
    urls = [ 'https://www.bmw.com',
    'https://www.vw.com',
    'https://www.mercedes-benz.com'
    ];
    <br/>
    for ( c = 0; c &lt; row.length; c ++ ) {
    row[ c ].addEventListener( 'dblclick', goto( c ), false );
    }

    function goto( c ) {
    return function() {
    w.location = urls[ c ];
    }
    }

    } ( window, document ) );


    Because getElementsByTagName returns a live HTMLCollection, which doesn't have a forEach method you'll have to either turn that HTMLCollection into an array or use querySelectorAll which return a non-live nodeList, if you want to use foreach.

    Below another version using forEach and bind instead of a closure.
    <i>
    </i>(function(w, d) {
    var url = '#/topics?';

    // var rows = Array.from(d.getElementsByTagName('tr'));
    var rows = d.querySelectorAll('#table tr');

    rows.forEach(function(row, idx) {
    row.addEventListener('dblclick', goto.bind(row, idx), false);
    });

    function goto(idx) {
    w.location = url + idx;
    };

    }(window, document));
    Copy linkTweet thisAlerts:
    @sibertauthorApr 15.2020 — > @Kever#1617418 Below another version using forEach and bind instead of a closure.

    This seems to work. I get the "table row id"

  • 1. Some website urls does not work however. Why?

  • 2. How do I fetch the row content "row content id"? /topic?id (1 = BMW)


  • https://jsfiddle.net/ds81f6wh/
    Copy linkTweet thisAlerts:
    @KeverApr 15.2020 — If all the urls you use start the same and only the number the changes you can store that url without a number and add the number in the goto() function. You might have to add 1 to the index, because rowIndex is 0-based.
    <i>
    </i> var url = '/topics?';
    ...
    function goto(idx) {
    w.location = url + (idx + 1);
    };

    If the urls are differencent, you can use the approach Coothead used in his post:
    <i>
    </i> var url = ['https://www.bmw.com',
    'https://www.vw.com',
    'https://www.mercedes-benz.com'
    ];
    ...
    function goto(idx) {
    w.location = url[idx];
    };
    Copy linkTweet thisAlerts:
    @sibertauthorApr 15.2020 — > @Kever#1617431 You might have to add 1 to the index, because rowIndex is 0-based.

    That is not that simple. A Row ID can be a mix of numbers and characters. It has no relation to the "table row ID". And It always points to the same final "card no". So I have to find the stored id (hidden or visible) in this table row and fetch the data from Postgresql and show the contents of this record.

    So the final url should be like this (I think) "topic/134F" or "topic/1234567896"

    And there could be thousands of records...

    http://94.237.92.101:3030/topics

    How do I get the record ID from the <tr>?
    Copy linkTweet thisAlerts:
    @SempervivumApr 15.2020 — A Row ID can be a mix of numbers and characters. It has no relation to the "table row ID". And It always points to the same final "card no". So I have to find the stored id (hidden or visible) in this table row[/quote]For such task I recommend using a data attribute like this:
    &lt;table id="table"&gt;
    &lt;tbody&gt;
    &lt;tr data-record-id="ABC88"&gt;
    &lt;td&gt;1&lt;/td&gt;
    &lt;td&gt;BMW&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr data-record-id="1412"&gt;
    &lt;td&gt;2&lt;/td&gt;
    &lt;td&gt;VW&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr data-record-id="XY666"&gt;
    &lt;td&gt;3&lt;/td&gt;
    &lt;td&gt;Mercedes&lt;/td&gt;
    &lt;/tr&gt;
    &lt;/tbody&gt;
    &lt;/table&gt;
    &lt;script&gt;
    const rows = document.querySelectorAll('#table tr'),
    url = 'topics/';
    rows.forEach((item, idx) =&gt; {
    item.addEventListener('dblclick', event =&gt; {
    console.log(url + item.dataset.recordId);
    // window.location.href = url + item.dataset.recordId;
    });
    });
    &lt;/script&gt;
    Copy linkTweet thisAlerts:
    @sibertauthorApr 15.2020 — > @Sempervivum#1617433 For such task I recommend using a data attribute like this:

    Thanks! Finally I got it to work. With some minor updates:

    https://jsfiddle.net/sbLa54wm/4/

    ``<i>
    </i> var rows = document.querySelectorAll('#table tr');
    var url = 'topics/';
    rows.forEach((item, idx) =&gt; {
    item.addEventListener('dblclick', event =&gt; {
    alert(url+item.dataset.id)
    });
    });<i>
    </i>
    ``
    Copy linkTweet thisAlerts:
    @sibertauthorApr 16.2020 — Some updates. There is minor changes to get it to work in real life.

    ``<i>
    </i>var rows = document.querySelectorAll('#table tr');
    var url = 'ctopic?id=';
    rows.forEach((item, idx) =&gt; {
    item.addEventListener('dblclick', event =&gt; {
    window.location.href = (url + item.dataset.id)
    });
    });<i>
    </i>
    `</CODE>

    The <STRONG>**ctopic?id=**</STRONG> makes it simpler to fetch the value in Go.

    <C>
    val := r.URL.Query().Get("id")`

    Live http://94.237.92.101:3030/mytopics

    Thanks for all help!
    ×

    Success!

    Help @sibert spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 3.29,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,

    tipper: @Samric24,
    tipped: article
    amount: 1000 SATS,

    tipper: Anonymous,
    tipped: article
    amount: 10 SATS,
    )...