skip to Main Content

On below code when I click the button it get disabled,

So I want when I click another button. disabled button gets enabled

Like Button 1 has been clicked and disabled,

when another button clicked like button 3, button 1 be enabled

its like 1 is clicked and disabled then when 2 is clicked and disabled then 1 gets enabled Like that

$(function () {
  $("#button1").click(function () {
    $("#button1").prop("disabled", true);
    $("p").text("You have clicked on Button 1");
    $(this).text("Selected");
  });
  $("#button2").click(function () {
    $("#button2").prop("disabled", true);
    $("p").text("You have clicked on Button 2");
    $(this).text("Selected");
  });
  $("#button3").click(function () {
    $("#button3").prop("disabled", true);
    $("p").text("You have clicked on Button 3");
    $(this).text("Selected");
  });
  $("#button4").click(function () {
    $("#button4").prop("disabled", true);
    $("p").text("You have clicked on Button 4");
    $(this).text("Selected");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="p-5">
  <button id="button1">Button 1</button>
  <button id="button2">Button 2</button>
  <button id="button3">Button 3</button>
  <button id="button4">Button 4</button>
  <p id="status" class="py-3"></p>
</div>

6

Answers


  1. There are many approaches, one could be the following:
    Adding a class to all the buttons to group them, store their values (id and original text) and bind click events to them as follow:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="p-5">
      <button class="button" id="button1">Button 1</button>
      <button class="button" id="button2">Button 2</button>
      <button class="button" id="button3">Button 3</button>
      <button class="button" id="button4">Button 4</button>
      <p id="status" class="py-3"></p>
    </div>
    <script type="text/javascript">
            $(function () {
                let buttons = $('.button'), buttonValues = [];
                buttons.each(function() {
                    let button = $(this);
                    buttonValues.push({
                        id: button.attr("id"),
                        text: button.text()
                    });
                });
    
                buttons.click(function() {
                    let id = $(this).attr("id");
                    
                    let storedText = buttonValues.find(item => item.id === id).text;
                    
                    buttons.each(function() {
                        let button = $(this);
                        button.prop('disabled', false);
                        let originalText = buttonValues.find(item => item.id === button.attr("id")).text;
                        button.text(originalText);
                    });
    
                    $(this).prop('disabled', true);
                    $(this).text('Selected');
    
                    $("p").text(`You have clicked on ${storedText}`);
                });
    });
        </script>
    Login or Signup to reply.
  2. you have to detect which button is disabled, to acheive that you can either iterate over all button or save the disabled button in a global variable.

    when you click a button start by enabling the disabled button, do your logic then disable the clicked button

    let disabled;
    
    $("#button1").click(function () {
        $("#button1").prop("disabled", true);
        $("p").text("You have clicked on Button 1");
        $(this).text("Selected");
    
         // enable the disabled one
        if(disabled) $(disabled).prop("disabled", false);
    
         // or find the disabled button then enable it
         document.querySelector("[disabled=true]")?.setAttribute("disabled", false);
    
        // now save our button as disabled
        disabled = "#button1";
    
      });
    
    Login or Signup to reply.
  3. You are repeating your code, which is not good design (see DRY)

    Instead I would recommend you take advantage of classes…

    • give each of your buttons the same class
    • give each of your buttons a data attribute to separate them
    • use a single event handler, rather than one each
    $(function () {
      $(".mybutton").click(function () {
        // Enable all buttons
        let $all = $(".mybutton").prop("disabled", false);
        // Reset text on each button
        $all.each((i, x) => $(x).text(`Button ${$(x).data("buttonid")}`));
        // Disable THIS button, and say it's selected
        let $btn = $(this).prop("disabled", true).text("Selected");
        // Set the hint
        $("p").text(`You have clicked on Button ${$btn.data("buttonid")}`);
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="p-5">
      <button id="button1" class="mybutton" data-buttonid="1">Button 1</button>
      <button id="button2" class="mybutton" data-buttonid="2">Button 2</button>
      <button id="button3" class="mybutton" data-buttonid="3">Button 3</button>
      <button id="button4" class="mybutton" data-buttonid="4">Button 4</button>
      <p id="status" class="py-3"></p>
    </div>
    Login or Signup to reply.
  4. As can be seen by the other answers, there are many ways to do what you want. One method that requires limited changes to your logic/code, is for each of your event handlers to call a function that enables all the buttons. That’s it! Add one short enableAll() function and call it at the beginning of each handler. See working code snippet below:

    function enableAll( ) {
      $("#button1").prop("disabled", false);
      $("#button2").prop("disabled", false);
      $("#button3").prop("disabled", false);
      $("#button4").prop("disabled", false);
    }
    $(function () {
      $("#button1").click(function () {
        enableAll();
        $("#button1").prop("disabled", true);
        $("p").text("You have clicked on Button 1");
        $(this).text("Selected");
      });
      $("#button2").click(function () {
        enableAll();
        $("#button2").prop("disabled", true);
        $("p").text("You have clicked on Button 2");
        $(this).text("Selected");
      });
      $("#button3").click(function () {
        enableAll();
        $("#button3").prop("disabled", true);
        $("p").text("You have clicked on Button 3");
        $(this).text("Selected");
      });
      $("#button4").click(function () {
        enableAll();
        $("#button4").prop("disabled", true);
        $("p").text("You have clicked on Button 4");
        $(this).text("Selected");
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="p-5">
      <button id="button1">Button 1</button>
      <button id="button2">Button 2</button>
      <button id="button3">Button 3</button>
      <button id="button4">Button 4</button>
      <p id="status" class="py-3"></p>
    </div>
    Login or Signup to reply.
  5. Here is a condensed way to do this. I used vanilla JS and jQuery. I’m sure you can condense it even more. If you use vanilla js you don’t need to add the jquery library

    Vanilla JS

    (function(){
        let buttonList = document.querySelectorAll('[id*=button]'),
        status = document.getElementById('status');
    
        buttonList.forEach(button => button.addEventListener('click', handleButton));
    
        function handleButton() {
            resetState();
            this.setAttribute('disabled', '');
            status.textContent = 'You have clicked ' + this.textContent;
        }
    
        function resetState() {
            buttonList.forEach(button => button.removeAttribute('disabled'))
        }
    })()
    

    jQuery

    $(function(){
        $('[id*=button]').on('click', handleButton);
    
        function handleButton() {
            $(this).parent().children().removeAttr('disabled');
            $(this).prop('disabled', true);
    
            $('#status').text('You have clicked ' + $(this).text())
        }
    })
    
    Login or Signup to reply.
  6. An other way…
    … shorter code in pure JS ?

    const pStatus = document.querySelector('p#status')
      ;
    document
    .querySelectorAll('button[data-txt]')
    .forEach( (btn,_,buttons_All) =>
      {
      btn.onclick =_=>
        {
        buttons_All.forEach( b => b.disabled = (b === btn) );
        pStatus.textContent = `You have clicked ${btn.dataset.txt}`;
        } 
      })
    button[data-txt]::before {
      content: attr(data-txt);
      }
    button[data-txt]:disabled::before {
      content: 'Selected';
      }
    <div class="p-5">
      <button id="button1" data-txt="Button 1"></button>
      <button id="button2" data-txt="Button 2"></button>
      <button id="button3" data-txt="Button 3"></button>
      <button id="button4" data-txt="Button 4"></button>
      <p id="status" class="py-3"></p>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search