Multiple buttons call JQuery, need to know which one was clicked - javascript

I have multiple buttons which can call the same JQuery function. Example of html:
<tr><td>...</td>
<td><button class="modify" name="8">Modify</button></td>
</tr>
<tr><td>...</td>
<td><button class="modify" name="9">Modify</button></td>
</tr>
and so on...
And my JQuery function:
$(function() {
var id = $("button").attr("name");
$("#dialog").dialog({
autoOpen: false,
height: 250,
width: 240,
modal: true,
buttons: {
"Submit": function() {
$( this ).dialog( "close" );
$.ajax({
url: 'my_http',
type: 'POST',
data: $my_data,
});
},
Cancel: function () {
$(this).dialog("close");
}
}
});
$(".modify").click(function () {
$("#dialog").dialog("open");
}
});
As you can see I need to now which button was clicked (I retrieve it's name at the beginning of the dialog function). But since its "clickability" is determined by the class, not id, I get the first id in the list (8 in this case, even though the 9th was clicked).
How can I know which one was clicked? If I use classes, I do not know ids (names), if I use ids, how can I know that it was clicked?

Inside the click() method:
$(".modify").click(function () {
/* 'this' is the clicked DOM node,
'$(this)' is the clicked DOM node wrapped in a jQuery object. */
var clickedButtonName = this.name;
/* or $(this).prop('name'), but don't use jQuery to access a property that
can be returned by the DOM API, it's needlessly expensive. */
$("#dialog").dialog("open");
}

You can use the first parameter of the click function like so:
Click here for live demo!
$(".modify").click(function (e) {
console.log(e.target);
});

Related

jQuery - cannot call methods on dialog prior to initialization

This one is really bugging me. I'm getting an error in my console of Uncaught Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'
$( function() {
$('#search_all_notes_input').dialog({
autoOpen: false,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
}
});
/* Make the Search div a button and open dialog on click */
$( "#search_all_button" ).button().click(function() {
$( "#search_all_notes_input" ).dialog( "open" );
});
});
$('#submit_search_all_button').click( function () {
var searchText = $('#search_all_text').val();
var query = location.search.split('=');
var urlMrn = query[1];
formData = { mnr: urlMRN, search_text: searchText };
console.log(formData);
//$.post('note_search.php', formData, getMatchedNotes(data));
$(this).dialog('close');
});
Any ideas? I'm using a button element inside my dialog div instead of a custom dialog button. Also, the script is loaded at the very end of my HTML page
The problem is you're calling the dialog('close') on the #submit_search_all_button button, not the #search_all_notes_input element that you originally created a dialog on.
Instead of $(this).dialog('close');, use this:
$('#search_all_notes_input').dialog('close');

Javascript + click function

I have a javascript function that calls another function, I am now facing a problem where I have to click a button twice to display a modal dialog box, I know the issue most likely lies in this line:
$('#dialog_link').click(function() because I already called 'modaldialog' with an onclick like this:
<input id="dialog_link" type="button" value="Save" onclick ="javascript:modaldialog();" />
How can I rewrite this line $('#dialog_link').click(function() to call function() without another click?
Thanks!
<script type="text/javascript">
function modaldialog() {
window.Page_ClientValidate();
if (window.Page_IsValid) {
$('#dialog_link').click(function() {
$('#dialog').dialog('open');
return false;
});
}}
</script>
<script type="text/javascript">
$(function() {
// Accordion
$("#accordion").accordion({ header: "h3" });
// Tabs
$('#tabs').tabs();
// Dialog
$('#dialog').dialog({
autoOpen: false,
width: 600,
modal:true,
close: function() {
document.getElementById('dialog').style.display = 'block';
document.getElementById('fade').style.display = 'None';
},
buttons: {
"Ok": function() {
$(this).dialog("close");
document.getElementById('dialog').style.display = 'block';
document.getElementById('fade').style.display = 'None';
},
"Cancel": function() {
$(this).dialog("close");
document.getElementById('dialog').style.display = 'block';
document.getElementById('fade').style.display = 'None';
}
}
});
// Dialog Link
//$('#dialog_link').click(function() {
// $('#dialog').dialog('open');
// return false;
//});
// Datepicker
$('#datepicker').datepicker({
inline: true
});
// Slider
$('#slider').slider({
range: true,
values: [17, 67]
});
// Progressbar
$("#progressbar").progressbar({
value: 20
});
//hover states on the static widgets
$('#dialog_link, ul#icons li').hover(
function() { $(this).addClass('ui-state-hover'); },
function() { $(this).removeClass('ui-state-hover'); }
);
});
</script>
I'm not sure what your goal really is, but I don't think .click(func) does what you think it does. Since .click(func) adds that function as a click event listener every time you execute this line you would get an additional function in the listener set. You seem to be running this in your onClick meaning every time someone clicks your link you'll add another listener that does the same thing ($('#dialog').dialog('open');). If you just want your verification to be done before substituting the onClick handler you'll have to unbind the current function as well, but you might be better off just doing the check every time and calling $('#dialog').dialog('open') inside your if (window.Page_IsValid) block.
If what you really want is for modaldialog to be called only once and $('#dialog').dialog('open'); to be executed that time and every consecutive clicks do the following inside your conditional:
$('#dialog_link').unbind('click', this);
var f = function () { $('#dialog').dialog('open') }; // Function to replace onClick function.
$('#dialog_link').click(f);
f(); // Execute replacement function after assigning it.

jQuery-UI Dialog

I'm new to jQuery, and now I want to use jQuery-UI Dialog to show a nice message with long text to the user. The problem is that I want that every row in my Html table will have a "More details" link that will cause the jQuery Dialog window to open with the text from this specific row.
What should I add to the code that came with the jQuery-UI Dialog example? :
// Dialog
$('#dialog').dialog({
autoOpen: false,
width: 600,
buttons: {
"Ok": function() {
$(this).dialog("close");
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
Thanks.
You're going to want to bind an event handler to each row (or, better, use ".delegate()" on the table), probably for "click":
$('#yourTable').delegate("tr", "click", function() {
var $row = $(this);
// setup code here, and then:
$('#dialog').dialog('open');
});
In that handler, you'll want to pull stuff from the row and populate something in the dialog to reflect the table row contents.
edit — If you want only clicks in specific columns to bring up the dialog, you can just change the selector in the call to ".delegate()". For example, you might give the clickable <td> cells class "info", so that you could then do this:
$('#yourTable').delegate("td.info", "click", function() {
var $cell = $(this), $row = $cell.closest('td');
// setup code ...
$('#dialog').dialog('open');
});
An alternative is to use the tiny jTruncate plugin.
http://blog.jeremymartin.name/2008/02/jtruncate-in-action.html

how to retrieve href value for an onclick event based on "class" selector in Javascript?

I have
Click to proceed
and following javascript. When I click on above link it displays the dialog box with 2 buttons. "return false;" stops the default event of link tag. But I need the functionality in which when I click "Yes, delete" to take me to other page by choosing href value of a onclicked anchor. I tried alert($(this).attr('id')); (as I thought I could pick up HREF value using "this.attr('href')") but it displays "dialog".
How do I make it work so that when I click on a link having class name "confirm_delete" it displays me dialog, and if I click cancel it stays on the page otherwise takes me to page according to href value.
$(".confirm_delete").click(function(){
$('<div id="dialog">Are you sure you want to delete?</div>').appendTo('body');
$("#dialog").dialog({
bgiframe: true, resizable: false, height:140, modal: true,
overlay: {
backgroundColor: '#000', opacity: 0.5
},
buttons: {
'Yes, Delete all items in recycle bin': function() {
$(this).dialog('close');
$(this).remove();
alert($(this).attr('id'));
},
Cancel: function() {
$(this).dialog('close');
$(this).remove();
}
}
});
return false;
});
Thank you.
First off: try not to use underscores in class names. I've read somewhere they may cause problemsn...
Well, here:
$('a.confirm-delete').click( function(event) {
if( !confirm('are you sure you want to go?') ) return false;
});
here I've usedd the javascript confirm dialog. You can easily replace that with a jquery modal dialog.
jrh
OK, I can retrieve value of HREF
by var url = $(this).attr('href'); just after the $(".confirm_delete").click(function(){
line. It gives me "test.php?id=123" Only thing left is create/retrieve full url and redirecting to that url.
Thanks
This should do the trick:
$(".confirm_delete").click(function(){
var $delete = $(this);
...
$("#dialog").dialog({
...
buttons: {
'Yes, Delete all items in recycle bin': function() {
$(this).dialog('close');
$(this).remove();
alert($delete.attr('id'));
}
}
});
return false;
});

Passing data to a jQuery UI Dialog

I'm developing an ASP.Net MVC site and on it I list some bookings from a database query in a table with an ActionLink to cancel the booking on a specific row with a certain BookingId like this:
My bookings
<table cellspacing="3">
<thead>
<tr style="font-weight: bold;">
<td>Date</td>
<td>Time</td>
<td>Seats</td>
<td></td>
<td></td>
</tr>
</thead>
<tr>
<td style="width: 120px;">2008-12-27</td>
<td style="width: 120px;">13:00 - 14:00</td>
<td style="width: 100px;">2</td>
<td style="width: 60px;">cancel</td>
<td style="width: 80px;">change</td>
</tr>
<tr>
<td style="width: 120px;">2008-12-27</td>
<td style="width: 120px;">15:00 - 16:00</td>
<td style="width: 100px;">3</td>
<td style="width: 60px;">cancel</td>
<td style="width: 80px;">change</td>
</tr>
</table>
What would be nice is if I could use the jQuery Dialog to popup a message asking if the user is sure he wants to cancel the booking. I have been trying get this to work but I keep getting stuck on how to create a jQuery function that accepts parameters so that I can replace the
cancel
with
cancel.
The ShowDialog function would then open the dialog and also pass the paramter 10 to the dialog so that if the user clicks yes then It will post the href: /Booking.aspx/Change/10
I have created the jQuery Dialog in a script like this:
$(function() {
$("#dialog").dialog({
autoOpen: false,
buttons: {
"Yes": function() {
alert("a Post to :/Booking.aspx/Cancel/10 would be so nice here instead of the alert");},
"No": function() {$(this).dialog("close");}
},
modal: true,
overlay: {
opacity: 0.5,
background: "black"
}
});
});
and the dialog itself:
<div id="dialog" title="Cancel booking">Are you sure you want to cancel your booking?</div>
So finally to my question: How can I accomplish this? or is there a better way of doing it?
jQuery provides a method which store data for you, no need to use a dummy attribute or to find workaround to your problem.
Bind the click event:
$('a[href*=/Booking.aspx/Change]').bind('click', function(e) {
e.preventDefault();
$("#dialog-confirm")
.data('link', this) // The important part .data() method
.dialog('open');
});
And your dialog:
$("#dialog-confirm").dialog({
autoOpen: false,
resizable: false,
height:200,
modal: true,
buttons: {
Cancel: function() {
$(this).dialog('close');
},
'Delete': function() {
$(this).dialog('close');
var path = $(this).data('link').href; // Get the stored result
$(location).attr('href', path);
}
}
});
You could do it like this:
mark the <a> with a class, say "cancel"
set up the dialog by acting on all elements with class="cancel":
$('a.cancel').click(function() {
var a = this;
$('#myDialog').dialog({
buttons: {
"Yes": function() {
window.location = a.href;
}
}
});
return false;
});
(plus your other options)
The key points here are:
make it as unobtrusive as possible
if all you need is the URL, you already have it in the href.
However, I recommend that you make this a POST instead of a GET, since a cancel action has side effects and thus doesn't comply with GET semantics...
In terms of what you are doing with jQuery, my understanding is that you can chain functions like you have and the inner ones have access to variables from the outer ones. So is your ShowDialog(x) function contains these other functions, you can re-use the x variable within them and it will be taken as a reference to the parameter from the outer function.
I agree with mausch, you should really look at using POST for these actions, which will add a <form> tag around each element, but make the chances of an automated script or tool triggering the Cancel event much less likely. The Change action can remain as is because it (presumably just opens an edit form).
I have now tried your suggestions and found that it kinda works,
The dialog div is alsways written out in plaintext
With the $.post version it actually works in terms that the controller gets called and actually cancels the booking, but the dialog stays open and page doesn't refresh.
With the get version window.location = h.ref works great.
Se my "new" script below:
$('a.cancel').click(function() {
var a = this;
$("#dialog").dialog({
autoOpen: false,
buttons: {
"Ja": function() {
$.post(a.href);
},
"Nej": function() { $(this).dialog("close"); }
},
modal: true,
overlay: {
opacity: 0.5,
background: "black"
}
});
$("#dialog").dialog('open');
return false;
});
});
Any clues?
oh and my Action link now looks like this:
<%= Html.ActionLink("Cancel", "Cancel", new { id = v.BookingId }, new { #class = "cancel" })%>
Looking at your code what you need to do is add the functionality to close the window and update the page. In your "Yes" function you should write:
buttons: {
"Ja": function() {
$.post(a.href);
$(a). // code to remove the table row
$("#dialog").dialog("close");
},
"Nej": function() { $(this).dialog("close"); }
},
The code to remove the table row isn't fun to write so I'll let you deal with the nitty gritty details, but basically, you need to tell the dialog what to do after you post it. It may be a smart dialog but it needs some kind of direction.
After SEVERAL HOURS of try/catch I finally came with this working example, its working on AJAX POST with new rows appends to the TABLE on the fly (that was my real problem):
Tha magic came with link this:
remove
remove
remove
This is the final working with AJAX POST and Jquery Dialog:
<script type= "text/javascript">/*<![CDATA[*/
var $k = jQuery.noConflict(); //this is for NO-CONFLICT with scriptaculous
function removecompany(link){
companyid = link.id.replace('remove_', '');
$k("#removedialog").dialog({
bgiframe: true,
resizable: false,
height:140,
autoOpen:false,
modal: true,
overlay: {
backgroundColor: '#000',
opacity: 0.5
},
buttons: {
'Are you sure ?': function() {
$k(this).dialog('close');
alert(companyid);
$k.ajax({
type: "post",
url: "../ra/removecompany.php",
dataType: "json",
data: {
'companyid' : companyid
},
success: function(data) {
//alert(data);
if(data.success)
{
//alert('success');
$k('#companynew'+companyid).remove();
}
}
}); // End ajax method
},
Cancel: function() {
$k(this).dialog('close');
}
}
});
$k("#removedialog").dialog('open');
//return false;
}
/*]]>*/</script>
<div id="removedialog" title="Remove a Company?">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>
This company will be permanently deleted and cannot be recovered. Are you sure?</p>
</div>
This work for me:
SPOSTA
function sposta(id) {
$("#sposta").data("id",id).dialog({
autoOpen: true,
modal: true,
buttons: { "Sposta": function () { alert($(this).data('id')); } }
});
}
When you click on "Sposta" in dialog alert display 100
Ok the first issue with the div tag was easy enough:
I just added a style="display:none;" to it and then before showing the dialog I added this in my dialog script:
$("#dialog").css("display", "inherit");
But for the post version I'm still out of luck.
Just give you some idea may help you, if you want fully control dialog, you can try to avoid use of default button options, and add buttons by yourself in your #dialog div. You also can put data into some dummy attribute of link, like Click. call attr("data") when you need it.
A solution inspired by Boris Guery that I employed looks like this:
The link:
<a href="#" class = "remove {id:15} " id = "mylink1" >This is my clickable link</a>
bind an action to it:
$('.remove').live({
click:function(){
var data = $('#'+this.id).metadata();
var id = data.id;
var name = data.name;
$('#dialog-delete')
.data('id', id)
.dialog('open');
return false;
}
});
And then to access the id field (in this case with value of 15:
$('#dialog-delete').dialog({
autoOpen: false,
position:'top',
width: 345,
resizable: false,
draggable: false,
modal: true,
buttons: {
Cancel: function() {
$(this).dialog('close');
},
'Confirm delete': function() {
var id = $(this).data('id');
$.ajax({
url:"http://example.com/system_admin/admin/delete/"+id,
type:'POST',
dataType: "json",
data:{is_ajax:1},
success:function(msg){
}
})
}
}
});
i hope this helps
$("#dialog-yesno").dialog({
autoOpen: false,
resizable: false,
closeOnEscape: false,
height:180,
width:350,
modal: true,
show: "blind",
open: function() {
$(document).unbind('keydown.dialog-overlay');
},
buttons: {
"Delete": function() {
$(this).dialog("close");
var dir = $(this).data('link').href;
var arr=dir.split("-");
delete(arr[1]);
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
Delete

Categories

Resources