Enable/disable a button using a function


#1

Hi,
I want to enable/disable a button after it has been pressed using a function. How do I do this? My current code won’t work. Also, how would I have the button automatically disabled, but then it would be enabled after another button has been pressed?

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="button" value="click me" onclick="buttonthing()" />
<script>
function buttonthing(){
  document.getElementById('buttonthing').disabled = true;
  }
</script>
</body>
</html>

Please fix it, thanks!
Tom


#2

disabled is an attribute, so we need a way to manipulate the attribute of an element, thankfully JS has this functionality:

https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute

we can just set the disable attribute on the <input> to disable the button by default

then we can use a use click event, and use getElementById to enable/disable another button, again using setAttribute to manipulate the attribute

it doesn’t work like that, we can help you, you will need to fix it :wink:


#3

Can you give me an example?
Sorry :sweat_smile:


#4

The documentation i provided contains an example? And you are very much in look it even contains an example of disabling a button

If i provide an answer, please take the time to actually read it.


#6

Hi,
I read through it thoroughly and changed some of my code to look like this, but it still doesn’t work @stetim94

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button id="buttonthing">Hello World</button>
<script>
var b = document.querySelector("buttonthing");

b.setAttribute("name", "helloButton");
b.setAttribute("disabled", "");

</script>
</body>
</html>

#7

Where did your click function go? Why did you decide to use querySelector? i only linked to the documentation to show setAttribute. You had to see how to implement it, not just copy paste code from documentation without a thought

currently, your querySelector will attempt to find a <buttonthing></buttonthing> element, which doesn’t exist


#8

ooohhhhh ok thanks, sorry


#9

No need to apologize, but its important to understand that i let you do most of the work to optimize your learning.

i could put it together in 5 minutes, and give it to you, but then you haven’t learned much.


#10

thanks for helping me learn :smiley: