I want to set the variable selectedColumnIndex
back to null after using it each time.
I need to be able to check that a new selectedColumnIndex
value has been set after each use. It could be used once or dozens of times in a row (it's for "cut and insert" functionality in a table-style UI component).
If I put a browser breakpoint at the variable var check
, selectedColumnIndex
will show as null
. But then if $(document).on('click', '.columnUpdatesInsert', function () { }
runs again without $(document).on('click', '.columnUpdates', function () { }
ever running, selectedColumnIndex
will be back to the previous value.
var selectedColumnIndex = null;
$(document).on('click', '.columnUpdates', function () {
selectedColumnIndex = $(this).attr("data-columnindex");
});
$(document).on('click', '.columnUpdatesInsert', function () {
if (selectedColumnIndex != null) {
// get variables from click element etc.
$(updateColumnPosition(tableId, selectedColumnIndex, newColumnIndex));
}
else {
alert("No column was selected to move.");
}
});
function updateColumnPosition(tableId, selectedColumnIndex, newColumnIndex) {
$.ajax({
type: "POST",
url: "/Task/UpdateColumnIndex",
data: { projectId: _projectId, tableId: tableId, selectedColumnIndex: selectedColumnIndex, newColumnIndex: newColumnIndex },
dataType: 'json',
success: function (data) {
if (data.success) {
// do other unrelated work
selectedColumnIndex = null; // this successfully sets it to null, but it is getting set back to the previous value before this code is explicitly setting it again.
var check = 0;
}
else {
// handle error
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status " " thrownError);
},
});
}
CodePudding user response:
Probably because you are passing selectedColumnIndex as an arg to the function it becomes a local to that function.
Try not passing the value selectedColumnIndex as arg and use it as global all the time.
var selectedColumnIndex = null;
$(document).on('click', '.columnUpdates', function () {
selectedColumnIndex = $(this).attr("data-columnindex");
});
$(document).on('click', '.columnUpdatesInsert', function () {
if (selectedColumnIndex != null) {
// get variables from click element etc.
$(updateColumnPosition(tableId, newColumnIndex));
}
else {
alert("No column was selected to move.");
}
});
function updateColumnPosition(tableId, newColumnIndex) {
$.ajax({
type: "POST",
url: "/Task/UpdateColumnIndex",
data: { projectId: _projectId, tableId: tableId, selectedColumnIndex: selectedColumnIndex, newColumnIndex: newColumnIndex },
dataType: 'json',
success: function (data) {
if (data.success) {
// do other unrelated work
selectedColumnIndex = null; // this successfully sets it to null, but it is getting set back to the previous value before this code is explicitly setting it again.
var check = 0;
}
else {
// handle error
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status " " thrownError);
},
});
}