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
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:
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
You are repeating your code, which is not good design (see DRY)
Instead I would recommend you take advantage of classes…
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:
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
jQuery
An other way…
… shorter code in pure JS ?