Search code examples
javascriptfunctionbuttondisabled-input

JavaScript function() for buttons disabled/enabled


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

Solution

  • 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>