Textarea empty should show a disabled button

I have a text box and a button. There are two classes of buttonEnabled and buttonDisabled. I want to apply buttonEnabled only when there is text in the text box. Therefore, if the user enters a text area, then the button looks turned on, and when he clears all the text, selecting and cutting it or vice versa. I want my button to look off. Also I want to do this only with javascript and for some reason I don't want to use jQuery.

+3
source share
3 answers

At the moment, the only way to make sure that you immediately get all the changes in the contents of the input is to poll it. This is because there are many possible ways to edit input without creating an event keyupor immediate change. Besides cutting and pasting, drag and drop, undo / redo, auto-complete, spell check ...

HTML5 offers an event inputthat will fire in all cases, for example, but browser support does not yet exist, unfortunately.

You can, of course, back up the survey to quickly check the general case when you receive an event. For instance:

function watchInput(input, callback) {
    var value= input.value;
    function check() {
        if (input.value!==value)
            callback.call(input, value);
        value= input.value;
    }
    input.onchange=input.onkeyup= check;
    setInterval(check, 400);
};

watchInput(document.getElementById('mytextarea', function(oldvalue) {
    document.getElementById('mybutton').className= this.value===''? 'buttonDisabled' : 'buttonEnabled';
});
+3
source

Handle the onblur event as well as the onkeyup event. Here is an example of simple Javascript.

<html>
<head>
<script>

function setClass()
{
    var area = document.getElementById('textarea');
    var button = document.getElementById('button');

    if (area.value.length == 0)
        button.className = "buttonDisabled"
    else
        button.className = "buttonEnabled"
}

</script>
</head>
<body>

<textarea id="textarea" onkeyup="setClass()" onblur="setClass()"></textarea><br />
<button id="button" class="buttonDisabled">Your Button<button>

</body>
</html>
+2

Enter the same code (that you wrote in the keyup event) on the blur event.

See this answer Deny entering multiple characters, e.g. '<', '>' in all input text windows using jquery

In this answer, this was done using jQuery, and the goal was different, but you can also do what you need without using jQuery.

0
source

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


All Articles