Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linked event listeners using jQuery

I have this HTML structure

<div class="buttons">
    <button data-icon="ui-icon-disk" class="save">Save1</button>
    <button data-icon="ui-icon-check" class="ok">OK1</button>
    <button data-icon="ui-icon-trash" class="delete">Delete1</button>
    <button data-icon="ui-icon-close" class="close">Close1</button>
</div>

There are many blocks in the page like this one.
Some buttons come with click handlers functions (save and delete buttons).

What I want to do is: if someone click on an ok button, the corresponding save button click bound function should run.

My code:

$('.save').click(function(){
    alert('save');
});
$('.ok').click(function(){
    $('.save').click();
});

This is wrong, when I click on a ok button all save buttons fires... not only the one within the same buttons group.

Demo illustrating my problem.

like image 252
ilyes kooli Avatar asked Dec 27 '22 23:12

ilyes kooli


1 Answers

Use $(this).siblings('.save').click() to select only siblings of the clicked button instead of all matching buttons in the whole document.

Demo: http://jsfiddle.net/ThiefMaster/nMnm7/2/
Docs: http://api.jquery.com/siblings/

like image 163
ThiefMaster Avatar answered Dec 29 '22 12:12

ThiefMaster