So I have this function called check1 which executes when you click a specific submit button (last say this is button1). Now i want a new function to execute when you click another button (last say button2) that checks whether the first button(and event thats linked to it) is clicked/ excecuted.
Example:
function check1 () {
document.getElementById("id1").innerText= "hello";
}
button1.addEventlistener("click", check1);
button2.addEventlistener("click", check2);
(The code i'm asking about:)
function check2 () {
if (button 1 is clicked/ check1 is executed) {
document.getElementById("id2").innerText= "hello you";
} else {
document.getElementById("id2").innerText= "First click the other button";
My code is quite complicated and since im not a native english speaker, it will be hard for me to explane. That's why im using this simple example. I only want to know how you (and if you) can check in javascript if a specific other button is click beforehand / how you can check in javascript if a other function is already been executed.
I hope you guys can help me!
CodePudding user response:
Your best option here is most likely to use custom attributes. You can then use Javascript to discern whether the custom attribute is added to the first button and if it's not present, then you can throw the error
document.getElementById("id1").setAttribute("clicked", "true");
This line will set the custom attribute on the button, then you can use the following to know if it it’s on the button
document.getElementById("id1").hasAttribute("clicked");
CodePudding user response:
If you don't need to worry about people F12 hacking then I'd add a hidden input:
<input type="hidden" value="0" id="btn_CheckValue"/>
Then have an onclick="buttonClicked()" on the button
function buttonClicked(){
document.getElementById("btn_CheckValue").value = "1";
}
Then do your function checks on the second button.
function check2 () {
let btnValue = document.getElementById("btn_CheckValue").value
if (btnValue == 1) {
document.getElementById("id2").innerText= "hello you";
} else {
document.getElementById("id2").innerText= "First click the other button";
An example: https://jsfiddle.net/tgm7avhb/51/