Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know element clicked within a table?

I'm trying get the element clicked within a TR in a HTML table. If I click on the Select input inside a TR, CurrentTarget field returns "TR", and OriginalTarget returns "SELECT".

This is my HTML:

<table id="0" class="tableEdit">
    <thead>
        <tr>
            <th name="id"></th>
            <th name="name">Descripción Registro</th>
            <th name="select">Fecha</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1651</td>
            <td>Name</td>
            <td>
                <select name="selectName">
                    <option value="1">1</option>
                    <option value="2">2</option>
                </select>
            </td>
        </tr>
    </tbody>
</table>

And this is my code:

            //trb is each TR element of the line
    $(trb).click(function(elem){
        if (elem.currentTarget && elem.currentTarget.tagName.toLowerCase() === "tr" && !isInput(elem.originalTarget)){
            if (editableRow){
                var rowTrigger = editableRow.find("button").get();
                $.editRow(rowTrigger,$.tableEditor.vault.getTableID($("#" + id)));
            }
    });

This code is working fine on my web browser, but it doesn't on mobile devices, because OriginalTarget returns undefined. Is there any way to get the original target on a mobile web browser?

like image 616
Amin Abu-Taleb Avatar asked Oct 16 '25 13:10

Amin Abu-Taleb


1 Answers

You haven't actually said what trb is but it sounds like it might be a set of the tr elements in your table.

What you're looking for is elem.target. That's the topmost element that was clicked, the one that initiated the event. (FWIW, I wouldn't call the argument passed to the event handler elem, it's an event, not an element.)

For instance, if you have:

<table>
<tbody>
<tr>
<td><span><strong>Click me</strong></span></td>
</tr>
</tbody>
</table>

...and this:

$("tr").click(function(e) {
    console.log(e.target.tagName);
});

...and you click the text "click me," you'll see

STRONG

...in the console.


Side note: It's handy to use closest with that if you want to know what cell or row was clicked, e.g.:

var $td = $(e.target).closest('td');
like image 97
T.J. Crowder Avatar answered Oct 18 '25 15:10

T.J. Crowder