I have some parts of a page which I am locking using a padlock icon in the top right. This updates the database and the icon changes from an open lock to a closed lock. I want the same icon to now be used to unlock the same data. What i am trying to do is change the onclick function from lockRun() to unlockRun() each time it is clicked. What is happening though is that is not only setting the onclick but executing the click aswell so it just goes from locked to unlocked constantly which isnt what I want! The code that is doing this loop is below.
function lockRun(runNum) {
var lockID = 'Lock' + runNum;
var runID = 'Run' + runNum;
var runIDCode = document.getElementById(lockID).dataset.runid;
console.log(runIDCode);
$.ajax({
url: '/runs/lock',
type: 'POST',
data: {
runCode: runIDCode
}
}).done(function (response) {
//console.log(siblings[1].dataset.contno);
var dbResponse = JSON.parse(response);
document.getElementById(lockID).classList.remove("fa-lock-open");
document.getElementById(lockID).classList.add("fa-lock");
document.getElementById(runID).classList.add('locked');
document.getElementById(lockID).onclick = unlockRun(runNum);
});
}
function unlockRun(runNum) {
var lockID = 'Lock' + runNum;
var runID = 'Run' + runNum;
var runIDCode = document.getElementById(lockID).dataset.runid;
console.log(runIDCode);
$.ajax({
url: '/runs/unlock',
type: 'POST',
data: {
runCode: runIDCode
}
}).done(function (response) {
//console.log(siblings[1].dataset.contno);
var dbResponse = JSON.parse(response);
document.getElementById(lockID).classList.remove("fa-lock");
document.getElementById(lockID).classList.add("fa-lock-open");
document.getElementById(runID).classList.remove('locked');
document.getElementById(lockID).onclick = lockRun(runNum);
});
}
So once the padlock icon is clicked, it is immediatley executing the unlock function then the lock function on repeat.