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');
}
}
});
});