jmcclane
jmcclane

Reputation: 189

jQuery select button from the closest <td>

I have a table like this:

<div id="somehting">
 <table>
    <tr>
       <td>
         <button id="example">...</button>
       </td>
       <td>
         <input type="text" class="text"/>
       </td>
    </tr>
  </table>
</div>

I want to get the button enabled/disabled when I have a keydown-event in the inputfield. To do so I put following listeners to the code:

$('#something').on('keydown', ".text", function(){   
   $(this).closest("td").find('#example').removeAttr('disabled');
});

But it does not work. How do I select the button in the td before the td of the inputfield?

Upvotes: 1

Views: 9916

Answers (2)

Milind Anantwar
Milind Anantwar

Reputation: 82241

First of all, you have used wrong parent selector in event delegation for textbox keydown.You have div id somehting and in event you are using something.try this:

 $('#somehting').on('keydown', ".text", function(){   
    $(this).closest("#somehting").find('#example').removeAttr('disabled');
 });

Working Demo

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388336

The button is in the same tr not in td, so you need to find the tr of the input element then find the button inside it

$(this).closest("tr").find('#example').removeAttr('disabled');

Note: If you have an ID then there is no need to use any other selector, just use the id selector. But if the tr structure is repeated then you will have multiple elements with the same id which is not valid so use a class attribute for the button instead of id.

So

<button class="example">...</button>

then

$(this).closest("tr").find('.example').removeAttr('disabled');

Upvotes: 5

Related Questions