Pregunta

I have a table full of appointments. Every appointment has two buttons. One for canceling the event, one for accepting it.

I am struggling to get the appointmentId in the jQuery function when I click on a button. Can you please give me a hint how to do this? The appointmentId is in the table as a hidden input field.

// my html code
<tr>
  <td align="left">
     <input type="hidden" name="appointmentId" value="234">
     John Smith - 14.03.2013 at 9 o'clock
  </td>
  <td align="right">
    <input type="button" id="acceptEvent" class="acceptEvent" value="Accept">
    <input type="button" id="cancelEvent" class="cancelEvent" value="Cancel">
  </td>
</tr>

// my jQuery code
$("body").delegate('.acceptEvent', 'click', function() {  
    console.log('accept event clicked');

    // get the appointmentId here

});

$("body").delegate('.cancelEvent', 'click', function() {  
    console.log('cancel event clicked');

    // get the appointmentId here
});
¿Fue útil?

Solución 2

In the click function, you have access to the button that was clicked with this so you can do:

$("body").on('click', '.cancelEvent', function() { 
     var input = $(this).closest('tr').find('input[name="appointmentId"]').val();
 });

Otros consejos

Use closest to grab the parent tr element, then select your hidden field. The reason that this is the correct answer is because it takes the context of the click event with $(this). Then it travels up the DOM tree to your root table row element and selects the child by name. This ensures that you are always in the correct row.

EDIT: I know you already selected an answer, but this was really bothering me that it wasn't working properly. I had to walk down twice using .children() to get it to work though you could also use .find('input[name="appointmentId"]'). Even though you've already selected your answer, I hope this will help you.

$('.acceptEvent').click(function() {
    var myVal = $(this).closest('tr').children().children().val();
}); 

$('.cancelEvent').click(function() {
    var myVal = $(this).closest('tr').children().children().val();
}); 

Assuming you have no other IDs or classes to key off of, you can use jQuery's Attribute Equals Selector in reference to the clicked button's parent tr element:

$('.acceptEvent').click(function() {
    // get the appointmentId here
    var appointmentId = $(this).closest('tr').find('input[name="appointmentId"]').val();
});

I'll do it like that :

$("body").on('.acceptEvent', 'click', function() {  

    var id = $('input[name="appointmentId"]').val();
    //Or search in the parent <tr> 
    var id = $(this).parent().find('input[name="appointmentId"]').val();

    console.log('accept event clicked');

    console.log('Id is ' + id);

});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top