I'm trying to code js for an html dialog which works with variables so it is reusable and I don't have to write the same redundant code each time I create a dialog. If user click "OK" then foo = true, and if user click "CANCEL" then foo = false. I want to asign a function name to a js variable ("run_me_true") and another variable ("run_me_false") both based on whether foo is true or false. And then run that function contained in the "run_me" variable(s).
function IT_true () {alert ("this is true");}
function IT_false () {alert ("this is false");}
// MAIN FUNCTION
function clear_data() { foo = false;
glass = 'ERASE the current player list?';
document.getElementById('show_confirm').innerHTML = glass;
var run_me_true = window['IT_true'];
var run_me_false = window['IT_false'];
openCONFIRM();}
// OPEN AND CLOSE DIALOG
function openCONFIRM() {
var dialogCONFIRM_O = document.getElementById("confirm_me");
dialogCONFIRM_O.showModal();
}
function closeCONFIRM() {
var dialogCONFIRM_C = document.getElementById("confirm_me");
dialogCONFIRM_C.close();
}
<!-- CONFIRM DIALOG -->
<div>
<dialog id="confirm_me">
<h3 id = "show_confirm"></h3>
<button onclick = "window[run_me_true]();" >OK</button>
<button onclick= "window[run_me_false]();" >CANCEL</button>
</dialog></div>
<!-- END CONFIRM DIALOG-->
question is a little odd but I’m guessing you mean this:
function your_func(){
// your code…
}
var run_me_true = window[‘your_func’];
run_me_true();
Since ‘window’ is technically an object, you can access any variable (including functions) using the square brackets with an object. Just put the name of the variable in quotations inside the brackets
<button onclick = "window[run_me_true]();" >OK</button>
<button onclick= "window[run_me_false]();" >CANCEL</button>