Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to toggle a button when another button is clicked?

I have 2 sample buttons, and what I need is when a user clicks on the second button, the first button will change its text.

Please see sample below:

$(document).ready(function() {
  $('#anchor-sample-btn').on('click', function() {
    var text = $('#anchor-sample-btn').text();
    if (text === "On") {
      $(this).html('Off');
    } else {
      $(this).text('On');
    }
  });
});
<script src="https://bbirdtools.netlify.app/_global-externals/scripts/3.4.1.jquery.min.js"></script>

<button class="outline" id="anchor-sample-btn">On</button>

<p> When the second btn is clicked, the first btn should change to <b>On</b> if it's <b>Off</b>, and vice versa</p>

<button class="outline">When I'm clicked, toggle the first btn on/off</button>

Also, how do I disable the first button when it’s clicked for 5 seconds to prevent double click?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

EDIT:

When the first btn is clicked, it should still change text and be disabled for 5 seconds.

The second button is just an alternative to perform the same function of the first btn, so it should toggle the first on/off.

Thanks a lot in advance!

>Solution :

You can do it in many ways, this is one way (not using jQuery).

const $btnOne = document.querySelector('#button-one');
const $btnTwo = document.querySelector('#button-two');

let buttonOneIsOn = true;

$btnTwo.addEventListener('click', () => {
  buttonOneIsOn = !buttonOneIsOn;
  $btnOne.innerText = buttonOneIsOn ? 'On' : 'Off';
});

$btnOne.addEventListener('click', () => {
  buttonOneIsOn = !buttonOneIsOn;
  $btnOne.innerText = buttonOneIsOn ? 'On' : 'Off';
  
  $btnOne.disabled = true;
  setTimeout(() => {
    $btnOne.disabled = false;
  }, 5000);
});
<button id="button-one">On</button>

<p>When the second btn is clicked, the first btn should change to <b>On</b> if it's <b>Off</b>, and vice versa</p>

<button id="button-two">When I'm clicked, toggle the first btn on/off</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading