1

I'd like to make a function on click on tabes first cell in each row only. This is table built with plugin and this method does not work

$('#ecoTableTotal').find('tr').find('td').eq(0).click(function(){
    console.log('click');
})

This one is working, but I need this to click only on the first cell. Is this possible?

 $('#ecoTableTotal').on('click', 'tr' , function (event) {
        console.log('click');
    });

EDIT: Table is generated using Bootstrap table (http://wenzhixin.net.cn/p/bootstrap-table/docs/index.html). This question is also about the same problem with click function.

Community
  • 1
  • 1
Anuket
  • 329
  • 8
  • 22

3 Answers3

2

Use :first-of-type selector: http://api.jquery.com/first-of-type-selector/

jsBin demo

As suggested elsewhere, :first-child will not work

  • it will not target the i element (as per your request) that are really the first i to appear. i.e: if before an i element you have a <br> or <b>bold</b> than i:first-child is not any more the first-child!

Seems from your comments that your TR are created dynamically, so do like

$('#ecoTableTotal').on("click", "tr td:first-of-type i:first-of-type", function(){
   console.log('click');
});

More info about how to use: use .on() with event delegation.


To resume, you can use this two variants:

"tr td:first-of-type i:first-of-type"

or

"tr td:first-child i:first-of-type"
// TD is always the first inside a valid TABLE TR so only here we can use 
// first-child, but there's no guarantee that a contextual <i> element is not 
// preceded by some other HTML element tag.
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
1

Selector > means that you are interested only in direct child element, it helps to define deph of your selector.

$('#ecoTableTotal').on('click', 'tbody > tr > td:first' , function (event) {
        console.log('click');
});
Beri
  • 11,470
  • 4
  • 35
  • 57
1
$('#ecoTableTotal').on('click', 'tr td:first-child' , function (event) {
    console.log('click');
});

EDIT

$('#ecoTableTotal').on('click', 'tr td:eq(0)' , function (event) {
    console.log('click');
});

EDIT

$('#ecoTableTotal').on('click', 'tr td:eq(0) i:eq(0)' , function (event) {
    console.log('click');
});
  • Thanks, only this one work. Could it be extended to click only on element (the only element) in this cell? – Anuket Dec 05 '14 at 08:25
  • @Anuket, kindly check my post –  Dec 05 '14 at 08:36
  • @Arvind in your example, using `('#ecoTableTotal').on('click', 'tr i:first-child' , function (event) {` will not target any more only the first `i` *`(c.)"inside this cell"`*, but also the *first `i`* inside every other cell. – Roko C. Buljan Dec 05 '14 at 08:39