Jquery how to get a button by opening a dialog

I have a dialog that opens with many buttons. How to find out which button opened this dialog?

$('#dialog').dialog({ autoOpen: false, buttons: { "Ok": function() { $(this).dialog("close"); }, "Cancel": function() { $(this).dialog("close"); } }, open: function(event, ui) { //HERE ::: how to get an HTML OBJECT TO THE ELEMENT THAT OPENED THE DIALOG } }); 

This is called:

 $('a').live('click',function(){ $('#dialog').dialog('open'); }); 

I want to know which <a> tag caused this dialog. Is it possible?

Thanks!

+4
source share
4 answers

In your .live() handler, you can save a link to the element that was clicked using .data() , for example:

 $('a').live('click',function(){ $('#dialog').data('opener', this).dialog('open'); }); 

Then, to get it later, you can grab it from $('#dialog').data('opener') or $.data(this, 'opener') in the case of the open (because this refers to the dialog element ) For example, your open function might look like this:

 open: function(event, ui) { $(this).html("Hi, I was opened by: " + $.data(this, 'opener').id); } 

This will show the id property of the anchor you clicked on to open the dialog ... you can do whatever you want, $.data(this, 'opener') refers to the <a /> DOM element.

You can try a demonstration of this here.

+16
source

making the assumption that you have a button like this:

 <input type="button" class="mybuttons" value="Click Me"/> 

and some css for example:

 .openerclass { background-color: red; } 

add this class when clicked

 $(function() { var myevent; $(".mybuttons").click(function(event){ myevent = $(event.target); $(".selector").dialog("open"); }); $(".selector" ).dialog({ open: function(event, ui) { var opener = $(event.target); myevent.addClass("openerclass"); alert(myevent.nodeName); ... } }); }); 

Edit: correct syntax error and add another example to clear it

Edit2: the original was wrong (sort of) in that the openener event is NOT associated with the click event. Modified to properly use the click event.

0
source

You can give it id:

 $('a').live('click',function(){ $('#dialogTrigger').removeAttr('id'); $(this).attr('id', 'dialogTrigger'); $('#dialog').dialog('open'); } open: function(event, ui) { // do something with $('#dialogTrigger') } 
0
source

You can assign $(this) variable of type me and use it later:

 $(".locked").on('click',function unlock(){ var me = $(this); buttons: { "Yes": function() { me.removeAttr('disabled').removeClass('locked'); } 
0
source

Source: https://habr.com/ru/post/1316323/


All Articles