kastulo
kastulo

Reputation: 851

Select a button with a class inside of a table with an id

I have the following code:

<table id="my_table">
<tr>
    <td>
        <button class="btn_save" value="1">Save</button>
    </td>
</tr>
</table>

I want to select that button

I have tried:

$('#my_table .btn_save').click......
$('table#my_table .btn_save').click......
$('table td .btn_save').click......
$('table td :button.btn_save').click......

nothing seems to work, what am I missing?

btw, I cant put an id on the button because this will be a dynamycally generated table with lots of buttons, thats why I chose the class way.

Upvotes: 3

Views: 4701

Answers (4)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276306

all your selectors seem ok. (Here is a working jsFiddle)

I see two possible issues:

Either your data is added dynamically, in which case you need to use event delagation using .on():

$(document).on("click",'#my_table .btn_save',function(){
   //what you're doing
});

The other possibility is that the selector is added before the data, in which case you need to put your statement in a $(document).ready clause

$(function(){
    $('#my_table .btn_save').click......
});

Upvotes: 4

j08691
j08691

Reputation: 207900

Since you're generating the table and contents dynamically, delegate the click event by using .on(). Try

$(document).on('click', '#my_table .btn_save', function(){......

Upvotes: 3

ITroubs
ITroubs

Reputation: 11215

It doesn't matter how often you click these buttons. It is not guaranteed that they submit your form! You will have to change them into type="submit" instead of type="button"

Upvotes: 0

Anoop
Anoop

Reputation: 23208

Make sure that table and button exist in dom while you running your code.

$(function(){
      var button = jQuery("#my_table button.btn_save")
});

Upvotes: 0

Related Questions