Javascript - power button when filling in input

I want to turn on my button when the input is full. I want to do this in pure Javascript.

My sample code in HTML:

<form action="sent.php" method="post" name="frm">
  <input type="text" name="name_input" id="name" onkeyup="myFunction()"><br>
  <button type="submit" class="button button-dark" id="send">Send message</button>
</form>

And Javascript:

document.addEventListener("DOMContentLoaded", function(event) {
    document.getElementById('send').disabled = "true";
    function myFunction() {
        var nameInput = document.getElementById('name').value;
        if (!nameInput === "") {
            document.getElementById('send').disabled = "false";
        } 
    }
});

I don’t know why my button does not change in order to enable the state after filling something in the input. I tried different ways to do this, but it still does not work. Please, help.

+4
source share
4 answers

The problem with your code is that it is myFunction()unavailable because you defined it in an eventlistener for a click.

Complete the reorganized code response:

HTML

<form action="sent.php" method="post" name="frm">
    <input type="text" name="name_input" id="name">
    <br>
    <button type="submit" class="button button-dark" id="send" disabled>Send message</button>
</form>

Js

document.getElementById("name").addEventListener("keyup", function() {
    var nameInput = document.getElementById('name').value;
    if (nameInput != "") {
        document.getElementById('send').removeAttribute("disabled");
    } else {
        document.getElementById('send').setAttribute("disabled", null);
    }
});
+1
source

HTML , disabled .

disabled , "false" "true", (http://www.w3schools.com/tags/att_input_disabled.asp)

, :

 document.getElementById('send').removeAttribute('disabled')
+7

,

 function myFunction() {
            document.getElementById('send').disabled = true;
            var nameInput = document.getElementById('name').value;
            if (nameInput != "") {
            alert("Empty");
                document.getElementById('send').disabled = false;
            }
    }

, , isNaN(), true, , false

0

, myFunction , input myFunction() onkeyup="myFunction()"

DOMContentLoaded

see demo section

document.addEventListener("DOMContentLoaded", function(event) {
    document.getElementById('send').disabled = "true";
});
function myFunction() {
    var nameInput = document.getElementById('name').value;
    console.log(nameInput);
    if (nameInput === "") {
        document.getElementById('send').disabled = true;
    } else {
        document.getElementById('send').disabled = false;
    }
}
0
source

Source: https://habr.com/ru/post/1666885/


All Articles