user544079
user544079

Reputation: 16629

selecting a table cell based on its id using jquery

I have the table set up as

<table class="tab1" width="400" cellpadding="20">
     <tr>
         <td id="cell1">Name</td>
         <td id="cell2">Company</td>
     </tr>
</table>

It is being accessed using

<script type="text/javascript">
     $(document).ready(function(){
         if($('#cell1').attr('click',true)) {
             alert("Cell 1 was clicked");
         }
     });     
</script>

I want the alert message to display when the cell1 is clicked. At present I do not get any output.

Upvotes: 0

Views: 145

Answers (6)

deformhead
deformhead

Reputation: 109

In your jQuery code, you need to target your element with its ID like that :

$('#cell1').click(function(){
    alert('cell1 was clicked');
});

If you want to be more general on targeting, do like that instead :

$('#my-table td').click(function(){
    alert($(this).attr('name')+' was clicked');
});

With this HTML code :

<table id="my-table" class="tab1" width="400" cellpadding="20">
     <tr>
         <td name="cell1">Name</td>
         <td name="cell2">Company</td>
     </tr>
</table>

With the second method, you could factorise your bind of LI clicks

Upvotes: 0

m33bo
m33bo

Reputation: 1354

As it is an ID I would directly attach it, attr is not what you are looking for.

$('#cell1').click(function(){
    alert('Cell1 has been clicked!');
});'

Hope this helps.

Upvotes: 0

Irfan TahirKheli
Irfan TahirKheli

Reputation: 3662

$('#cell1').on('click',function(){
       alert("Cell 1 was clicked");
 });

Upvotes: 1

Max Malyk
Max Malyk

Reputation: 860

Your jquery selector has to select proper cell and attach onclick handler to it like such:

$('td#cell1').on('click', function(){
    alert('cell1 clicked');
});

Upvotes: 1

oceanexplorer
oceanexplorer

Reputation: 1229

Try

$("td#cell1").click(function() {
  alert("Cell 1 was clicked")
});

Upvotes: 0

j08691
j08691

Reputation: 207901

Try:

$('td').click(function(){
    if(this.id=='cell1') alert('cell1 clicked');
});

jsFiddle example

You need to use the click event, not an attribute (attr()). Depending on what you need, you could also just bind directly to the cell with ID of cell1 with $('#cell1').click(function(){...})

Upvotes: 2

Related Questions