Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - enabling button when input is filled

I want to enable my button, when input is filled. I want to do it in pure Javascript.

My code example 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 is not changing to enable state after filling something in input. I have tried diffrent ways to do it, but it's still not working. Please help.

like image 500
Artanor Avatar asked Jan 16 '17 09:01

Artanor


People also ask

How do you disable submit button until form is filled?

Just click f12 in your browser, find the submit button in the html, and then remove the disabled ! It will submit the form even if the inputs are empty.

What is enable and disable button based on condition?

When User inputs a value in TextBox, first the Button is referenced. Then the value of the TextBox is checked. If the TextBox has value, the Button is enabled and if the TextBox is empty, the Button is disabled using JavaScript.


2 Answers

An input element in HTML is enabled only when the disabled attribute is not present.

In your case disabled is always present in your element, it's just that it has a "false" or a "true" value - but this is meaningless according to the specs (http://www.w3schools.com/tags/att_input_disabled.asp)

So you need to remove it altogether:

 document.getElementById('send').removeAttribute('disabled')
like image 155
Ovidiu Dolha Avatar answered Oct 20 '22 04:10

Ovidiu Dolha


The problem with your code is that myFunction() isn't available because you defined it in the eventlistener for click.

Complete refactored code answer:

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);
    }
});
like image 38
sandrooco Avatar answered Oct 20 '22 05:10

sandrooco