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;
}
3

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.