0

I have two buttons in my HTML:

<form>
<input type="button"  id="button1" value="Clickable" onClick="switchButton()">
<input type="button"  id="button2" value="Not Clickable" onClick="switchButton2()" disabled="true">
</form>

I want to write a function() in JavaScript for when I click on button1 it should be disabled and change it's value to "not clickable" and button2 should be enabled and change it's value to "clickable" and the other way around.

I have written two functions but they aren't correct and I am very new to JavaScript. This is my functions():

function switcher() {
var btn = document.getElementById("knapp1");
btn.disabled = true;
}
function switcher2(){
var btn2 = document.getElementById("knapp2");
btn2.enabled = true;
}
firajk
  • 33
  • 1
  • 6
  • There is no `enabled` property. And you might wanna switch vice-versa, just as you said – Jonas Wilms Mar 31 '18 at 14:15
  • 1
    https://stackoverflow.com/questions/13831601/disabling-and-enabling-a-html-input-button – epascarello Mar 31 '18 at 14:17
  • Possible duplicate of [Disabling and enabling a html input button](https://stackoverflow.com/questions/13831601/disabling-and-enabling-a-html-input-button) – bugs Mar 31 '18 at 14:22

2 Answers2

2

You have a problem with the name of your function : switchButton() in your html and switcher in your js, the id are different too and enabled is not an html property. You can achieve what you want with only one function :

function switchButton(btn1, btn2) {
    var btn1 = document.getElementById("button"+btn1);
    var btn2 = document.getElementById("button"+btn2);
    btn1.disabled = true;
    btn1.value = "not clickable";
    btn2.disabled = false;
    btn2.value = "clickable";
}
<form>
<input type="button" id="button1" value="Clickable" onClick="switchButton(1,2)">
<input type="button" id="button2" value="Not Clickable" onClick="switchButton(2,1)" disabled="true">
</form>
Nico_
  • 1,388
  • 17
  • 31
2

You should try to avoid have this duplicate logic that make the same, is very hard to maintain, I recommend to you instead use this:

function clickButton(e) {
  const currentBtn = document.getElementById(e);
  const otherBtn = document.getElementById(e === "knapp2"? "knapp1": "knapp2");
 
  currentBtn.disabled = true;
  otherBtn.disabled = false;
  currentBtn.value="Not Clickable"
  otherBtn.value="Clickable"
}
<form>
<input type="button"  id="knapp1" value="Clickable" onClick="clickButton('knapp1')">
<input type="button"  id="knapp2" value="Not Clickable" onClick="clickButton('knapp2')" disabled>
</form>
Miguel Angel
  • 944
  • 8
  • 20