Balubs Balubs - 3 months ago 6
HTML Question

Get HTML component from which button was pressed

How do I get the HTML component that contains the button which has been clicked with jQuery? After a button is clicked I need to get the invite object that corresponds to the clicked button and send a post request to a given link.

{% if invites %}
{% for invite in invites %}
<p>Your invites:</p>
<div class="row">
<label style="display: block">Invite from {{ invite.initiator }} to join his conference!</label>
<button type="button" id="ButtonId">Accept invite</button>
</div>
{% endfor %}
{% endif %}


The script:

<script type="text/javascript">
$(function() {

$('#ButtonId').on('click',function(){
!$(this).hasClass('ButtonClicked') ? addClass('ButtonClicked') : '';
$('#ButtonId').val('Done');
var data = {

};

$.ajax({
url: '/api/send_invite/' + /*the username*/,
data: JSON.stringify(data , null, '\t'),
contentType: 'application/json;charset=UTF-8',
type: 'POST',
success: function() {
}
});
});

});
</script>

Answer

Your "HTML component" is what the button is wrapped in ? If so, In order to get the element that contains the button that is being clicked (the "parent" of the button) you can do something like this:

$('#myButton').on('click',function(){
    var buttonParent = $(this).parent();
    // do your stuff..
});

For getting the "invite object" you can attach a data attribute to the accept-invite button, this data attribute will contain a value that you will use to fetch the correct object, for an example:

<button type="button" id="inviteAcceptBtn" data-object-id="123">Accept invite</button>

Then you can get that "object-id" with simple jQuery:

$('#inviteAcceptBtn').on('click',function(){
    var objectId = $(this).data('object-id');
    // do your stuff..
});

There are probably a handful of other methods, as there are many techniques to do this.

Hope it helps a bit