Juan Solana
Juan Solana

Reputation: 157

Adding an onclick event to a button with a button that has an onclick event?

I have 2 buttons, one has an onclick event that when clicked calls a function that is supposed to add an onclick event handler to the second button.

I was able to do this little example in w3schools.com, here is the code:

<!DOCTYPE html>
<html>
<body>

<p>Click "Try it" to execute the displayDate() function.</p>

<button id="myBtn2" onclick="addfunc();">Trigger</button>
<button id="myBtn">Try it</button>


<p id="demo"></p>

<script>
function addfunc(){
document.getElementById("myBtn").onclick = displayDate();
}

function displayDate() {
    document.getElementById("demo").innerHTML = Date();
}
</script>

</body>
</html> 

The intended function is that when clicking "Try it" button before "Trigger", nothing happens, and only after clicking "Trigger" the "Try it" button should work. Problem is when I click "Trigger" it actually runs the function that it is supposed to be executed by the click of "Try it" button.

Hope I explained myself, thanks!

Upvotes: 1

Views: 4291

Answers (2)

ecsIsAFK
ecsIsAFK

Reputation: 1

You can disable the second button (in HTML code) and make a first button an activator of btn1

<body>
  <main>
    <input class="btn1" type="button" value="enable button 2" name="btn1" onclick="ableBtn2()">
    <button Id="btn2" onclick="displayDate()" disabled="true">button 2</button>

    <p id="test"></p>

    <script type="text/javascript">
      function ableBtn2() {
        document.getElementById("btn2").disabled = false;
      }
    </script>
    <script type="text/javascript">
      function displayDate() {
        document.getElementById("test").innerHTML = Date();
      }
    </script>
  </main>
</body>

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 121998

You should use displayDate instead of displayDate(). Because displayDate() directly calls the function.

<!DOCTYPE html>
<html>
<body>

<p>Click "Try it" to execute the displayDate() function.</p>

<button id="myBtn2" onclick="addfunc();">Trigger</button>
<button id="myBtn">Try it</button>


<p id="demo"></p>

<script>
function addfunc(){
document.getElementById("myBtn").onclick = displayDate;
}

function displayDate() {
    document.getElementById("demo").innerHTML = Date();
}
</script>

</body>
</html> 


If you want to pass variables

<!DOCTYPE html>
<html>
<body>

<p>Click "Try it" to execute the displayDate() function.</p>

<button id="myBtn2" onclick="addfunc();">Trigger</button>
<button id="myBtn">Try it</button>


<p id="demo"></p>

<script>
function addfunc(){
   
document.getElementById("myBtn").addEventListener('click', function(){
     displayDate("my params");
});
}

function displayDate(params) {
    document.getElementById("demo").innerHTML = Date() + " -- " + params;
}
</script>

</body>
</html> 

Upvotes: 1

Related Questions