How do I get the onclick variable into a dialog function - javascript

I have a onclick event that has a value in it that I want to post to a backend php script. Just not sure how to get it in the dialog function.
function reorder(job_index)//<--------this fella
{
$('#dialog').dialog('open');
}
$(document).ready(function(){
$(function() {
$("#dialog").dialog({
bgiframe: true,
autoOpen: false,
height: 250,
width: 600,
modal: true,
buttons: {
'Yes, use the number above': function() {
var jobID=$("#jobnumber").val();
$.post("rpc.php", {
job_index:job_index,// <-------to here
jobID:jobID,
method: "reorder"
},
function(data,textstatus)
{
alert(data.message);
}, "json");
},
'No, create a new number for me': function() {
$(this).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
}
});
});
});
The value is job_index. Any tips?
Thanks

In the below code, I'm using a single function that will allow you to both store and retrieve your index.
The function index is creating a closure by returning declaring and returning another function. This means that the variable _index will still be available (think of it as like the variable was allocated on the heap instead of the stack-frame; ie malloc-ed) once the (outer) function has returned, and as you can see the function is self-invoking, due to the }(); on the last line of the function, thus returning immediately during parsing.
Then when you call the function index again (which now you will be basically calling the inner function that takes one formal argument, ind), you can pass in your index and if you do, the function will store it in the _index variable that I mentioned earlier on...ie the variable that is still available after the outer function returned.
If you don't pass in an argument (ie invoke the function like such: index()), the function only returns your stored variable. The logic behind this is that if a parameter is not passed, the value of the actual argument is undefined. Thus the function checks if the value is undefined, and if it is, it justs returns your variable.
And btw, you have a nested ready function inside your outer ready function. This is because $(function() { is the same as $(document).ready(function(){. I fixed this in the below code:
var index = function () {
var _index;
return function (ind) {
if (typeof ind !== "undefined") {
_index = ind;
}
return _index;
};
}();
function reorder(job_index)
{
index(job_index);
$('#dialog').dialog('open');
}
$(function () {
$("#dialog").dialog({
bgiframe: true,
autoOpen: false,
height: 250,
width: 600,
modal: true,
buttons: {
'Yes, use the number above': function () {
var jobID = $("#jobnumber").val();
$.post("rpc.php", {
job_index: index(),
jobID: jobID,
method: "reorder"
},
function (data, textstatus) {
alert(data.message);
},
"json");
},
'No, create a new number for me': function () {
$(this).dialog('close');
},
Cancel: function () {
$(this).dialog('close');
}
}
});
});
Another way to do it is by using the data method that nickf mentioned. This will allow you to store the index directly as part of your element, like such:
function reorder(job_index)
{
$('#dialog').data("job", job_index).dialog('open');
}
$(function () {
$("#dialog").dialog({
bgiframe: true,
autoOpen: false,
height: 250,
width: 600,
modal: true,
buttons: {
'Yes, use the number above': function () {
var jobID = $("#jobnumber").val();
$.post("rpc.php", {
job_index: $("#dialog").data("job"),
jobID: jobID,
method: "reorder"
},
function (data, textstatus) {
alert(data.message);
},
"json");
},
'No, create a new number for me': function () {
$(this).dialog('close');
},
Cancel: function () {
$(this).dialog('close');
}
}
});
});

You could store it as data on the element using .data()

Create a global variable, store the last clicked job_index there, and read it from there in the click handler.
var last_job_index;
function reorder(job_index)
{
last_job_index = job_index;
$('#dialog').dialog('open');
}
//snip
$.post("rpc.php", {
job_index: last_job_index,
jobID: jobID,
method: "reorder"
},
Warning: This is quite an unprofessional solution (shared mutable state)

Related

Concatenation of dynamic integer with id

I am working on a project and this is the relevant code for the problem
function calldiv(c)
{
$("modal_dialog").dialog({
title: "Approach with your deal",
buttons: {
Close: function () {
$(this).dialog('destroy')
}
},
modal: true
});
}
Here what I want is to attach value of c with modal_dialog on runtime i.e if c = 1 then next line becomes modal_dialog1 .
Thanks
Concat c with the string used to target modal_dialog:
function calldiv(c)
{
$("modal_dialog"+c).dialog({
title: "Approach with your deal",
buttons: {
Close: function () {
$(this).dialog('destroy')
}
},
modal: true
});
}

Show/Hide print button in JQuery?

I was wondering is there any way to show print button based on the argument passed in the function. Here is my code that creates dialog box:
alertInfo: function (message, title, height, width, print) {
$("<div></div>").dialog( {
buttons: {
"Ok": function () {
$(this).dialog("close");
},
//show/hide button if argument 'print' equals to 'Yes'
"Print": function() {
$(this).dialog().printArea();
},
},
close: function (event, ui) { $(this).remove(); },
resizable: false,
title: title,
modal: true,
width: height,
height: width,
overflow:'auto',
position: {
my: "center",
at: "center",
of: window
}
}).html(message);
}
This is the code where I'm passing the arguments in alerInfo() function:
$.alertInfo(infoTable,'User Info',800,600,'Yes');
I still did not get this to work and If I tried to put if statement around Print button error occurred. If anyone can help please let me know.
alertInfo: function(message, title, height, width, print) {
var buttons = {
"Ok": function() {
$(this).dialog("close");
}
};
if (print) buttons.print = function() {
$(this).dialog().printArea();
};
$("<div></div>").dialog({
buttons: buttons,
close: function(event, ui) {
$(this).remove();
},
resizable: false,
title: title,
modal: true,
width: height,
height: width,
overflow: 'auto',
position: {
my: "center",
at: "center",
of: window
}
}).html(message);
}
This assumes the print parameter is a boolean
$.alertInfo(infoTable,'User Info',800,600, true); // to show print button
$.alertInfo(infoTable,'User Info',800,600, false); // to not show print button
You're effectively passing an object to the buttons property:
{
"Ok": function () {
$(this).dialog("close");
},
"Print": function() {
$(this).dialog().printArea();
}
}
So what you can do is dynamically create that object based on your conditions and then set the dynamically created object to the property. It might look something like this:
// create the object
var myButtons = {
"Ok": function () {
$(this).dialog("close");
}
};
// conditionally add a "print" button
if (someCondition) {
myButtons.Print = function() {
$(this).dialog().printArea();
}
}
// use the object
$("<div></div>").dialog( {
buttons: myButtons,
close: function (event, ui) { $(this).remove(); },
// etc.
});

controller action execute two times with Ajax.ActionLink and JQuery UI Dialog

I have ajax.actionlink
#Ajax.ActionLink("Click here",//link text
"Insert", // action name
"Projects", // controller
new { poz = item.itemID.ToString() }, // route values
new AjaxOptions() { HttpMethod = "GET", UpdateTargetID = "PrjDiv" OnSuccess = "Initiate_Dialog" }, // ajax options
new { #class = "openDialog", #id = item.idemID.ToString() } //htmlAttributes
)
and jQuery UI dialog
function Initiate_Dialog() {
var itemID= $(this).attr("id").replace("item_", "");
var prjID= $("#m_project").val();
var url = encodeURI("/Projects/Insert?poz=" + itemID+ "&proj=" + prjID);
$("#dialog-edit").dialog({
title: 'Insert',
autoOpen: false,
resizable: false,
height: 'auto',
width: 650,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
open: function (event, ui) {
$(this).load(url);
},
close: function (event, ui) {
$(this).dialog('close');
},
buttons: {
Cancel: function () {
$(this).dialog("close");
}
}
});
$("#dialog-edit").dialog('open');
return false;
}
When i click on generated link, my controller action is executed 2 times. Once with parameters sent from ajax.actionlink, and second time, with parameters sent from javascript.
I know that i have 2 calls and that's why is action executed twice. My question is, is there a way around this to execute only call from javascript, and not from actionlink?

jQuery UI dialog with boolean return - true or false

I´m trying to do an replacement for the javascript confirm(). I have found the jquery dialog() function that can be fully customized. The problem is that i cant make it return true or false.
Here is my code:
$('#delBox').dialog(
{ autoOpen: false, resizable: false, modal: true, closeOnEscape: true, width: 300, height: 'auto', title: 'Deletar registro',
buttons: {
"Ok": function () {
return true;
}, "Cancelar": function () {
$(this).dialog("close");
return false;
}
},
open: function () {
var buttonsSet = $('.ui-dialog-buttonset').find("button:contains('Ok')");
buttonsSet.attr("class", "ui-button ui-state-default");
$('.ui-dialog-titlebar-close span').empty();
$('.ui-dialog-buttonset').find("button:contains('Ok')").button({
text: false,
icons: {
primary: 'ui-icon-ok'
}
});
$('.ui-dialog-buttonset').find("button:contains('Cancelar')").button({
text: false,
icons: {
primary: 'ui-icon-cancel'
}
});
}
});
This only return an object before any option selected:
function deletar() {
alert($('#delBox').dialog('open'));
}
jQueryUI dialog boxes can't return a true or false as they're shown on top of other content but without blocking execution.
The best you can do is:
make the box modal so that it hides the other content
supply callbacks to be used depending on which option is chosen.
For extra bonus points, you could create a $.Deferred() promise object and return that when you show the dialog. You can then resolve or reject that promise in the button event handlers.
This would give you clean separation between showing the dialog box, and performing the actions subsequently triggered by it:
function showDialog() {
var def = $.Deferred();
// create and/or show the dialog box here
// but in "OK" do 'def.resolve()'
// and in "cancel" do 'def.reject()'
return def.promise();
}
showDialog().done(function() {
// they pressed OK
}).fail(function() {
// the pressed Cancel
});
// NB: execution will continue here immediately - you shouldn't do
// anything else now - any subsequent operations need to be
// started in the above callbacks.
The first answer is fine - I thought I'd just add a bit of code showing how you can return the button that was clicked:
function ShowYesNoMessage(title, message) {
var def = $.Deferred();
$("#infoMessage").html(message);
$("#dialog_infoMessage").dialog({
modal: true,
title: title,
buttons: {
Yes: function () {
$("#infoMessage").html("");
$(this).dialog("close");
def.resolve("Yes");
},
No: function () {
$("#infoMessage").html("");
$(this).dialog("close");
def.resolve("No");
}
}
});
return def.promise();
}
$.when(ShowYesNoMessage("Are you sure", message)).then(
function(status) {
if (status == "Yes") {
//do the next step
}
}
);

Javascript scoping issue

I am trying to build a generic ajax loader, while ajax is running a lightbox with animated "Loading" gif will be displayed.
I have some issues with scoping.
The code is:
var t=setTimeout( "s.d.dialog( 'destroy' )" ,(s.o.msgTime*1000));
The error is: "Uncaught ReferenceError: s is not defined"
;(function ($) {
$.loader = function (data, options) {
return $.loader.impl.init(data, options);
};
$.loader.close = function (data) {
$.loader.impl.close(data);
};
$.loader.create = function () {
$.loader.impl.create();
};
$.loader.defaults = {
appendTo: 'body',
autoCreate: true,
msgTime: 5,
};
$.loader.impl = {
d: {},
init: function(data, options){
var s = this;
s.o = $.extend({}, $.loader.defaults, options);
if ((typeof data === 'object')&&!(data instanceof jQuery)&&data.url) {
data.success = function(data, textStatus, jqXHR){ $.loader.close(); }
data.error = function(jqXHR, textStatus, errorThrown){ $.loader.close('Error accessing server'); }
$.ajax(data);
}else if(s.o.autoCreate){
s.create();
}
return s;
},
create: function() {
var s = this;
s.d = $('<div id="dialog" style="display:hidden"><span style="width: 100%" id="loading_diag"><center><img src="http://www.mydomain.com/images/ajax-loader.gif" /></center></span></div>').appendTo(s.o.appendTo);
s.d.dialog({ title: 'Loading ...', dialogClass: 'noTitleStuff', modal: true, draggable: false, resizable: false });
},
close: function(data)
{
var s = this;
//alert(typeof s.d);
if ((typeof data === 'string')&&data) {
$("#loading_diag").hide();
$("#dialog").html(data);
var t=setTimeout( "s.d.dialog( 'destroy' )" ,(s.o.msgTime*1000));
}else{
s.d.dialog( "destroy" );
}
s.d= {};
},
};
})(jQuery);
If anybody knows how to solve it please share.
The first and second solution did something but havent fixed it completely,
now i am getting a different error: "Uncaught TypeError: Object # has no method 'dialog' $.loader.impl.close.s.d"
This will make it work:
var t = setTimeout(function() { s.d.dialog('destroy'); }, s.o.msgTime * 1000);
When you pass a string into setTimout, then that string (code) executes in global code - and since s is a local variable, it is indeed not defined in global code.
When you pass a string to setTimeout, the code in the string is executed in the context of the window object. Since window.s doesn't exist, you get the error. You can pass a closure to setTimeout to keep your s variable in scope like this:
var t = setTimeout(function() {s.d.dialog('destroy'); }, s.o.msgTime * 1000);

Categories

Resources