0

This should be an easy one for those who have the knowledge.

I’ve started getting my head into Javascript and thought about developing some forms e.g. adding buttons and firing different functionality.

What I have discovered is if you have onclick events on two different forms they seem to work and then reset themselves e.g. on one form I have a button that will disable another button on another form. However the button gets disabled then instantly enabled.

If I move the disabling button off the form then the functionality works as expected.

So, what should I be coding so that a button on one form will disable another button on another form without the button instantly enabling itself?

Many thanks for your time!

Its obvious when you know the ‘how’. If you know the ‘how’ pass it on.

...html

<body>
    <form class="form1" id="form1">
        <input type="button" id="btn01" value="OK">
        <p>From One!</p>
        <p id="p01">I am different.</p>
        <br/>
    </form>
    <br/>
    <form class="form2" id="form2">
        <br/>
        <!-- When the disable button is clicked the OK button gets disabled off
        but instanlty gets enabled again -->
        <button onclick="disableElement()">Disabled</button>
        <button onclick="enableElement()">Enable</button>
        <p>Click to disable the 'OK' button</p>
    </form>

    <!-- This works -->
    <button onclick="disableElement()">Disabled</button>
    <button onclick="enableElement()">Enable</button>
</body>

...

...Javascript //data.js

var onOff = false;

function disableElement() {
    if (onOff == false) {
        console.log("switched off")
        document.getElementById("btn01").disabled = true;
        onOff = true;
    }
}

function enableElement() {
    if (onOff == true) {
        console.log("enabled")
        document.getElementById("btn01").disabled = false;
        onOff = false;
    }
}

...

...css /* data.css */

#form1 {
    width: 500px;
    height: 250px;
    background-color: #b94813;
    border-left: 10px solid #000;
    border-right: 10px solid rgb(211, 17, 17);
}

#form2 {
    width: 500px;
    height: 250px;
    background-color: #8955cc;
    border-left: 10px solid #000;
    border-right: 10px solid rgb(211, 17, 17);
    ;
}

#p01 {
    color: blue;
}

...

col
  • 3
  • 1

1 Answers1

0

The answer is simple. You have omitted specifiying the type of your buttons, so they get their default type, which is submit. So clicking your button first executes your onclick Javascript, then immediately submits your form, which makes the page reload and resets your Javascript state to that of a freshly loaded page.

Simply set the button type to button:

<button onclick="disableElement()" type="button">Disabled</button>
<button onclick="enableElement()" type="button">Enable</button>
connexo
  • 53,704
  • 14
  • 91
  • 128