Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

textarea empty should show disabled button

I am having a textarea and a button. There are two classes buttonEnabled and buttonDisabled. I want to apply buttonEnabled only when there is some text in the textarea. So if user is typing in a textarea then button looks enabled and when he clears all the text either by selecting and cutting it or by backspace. I want my button to look disabled. Also i want to do this only with javascript and for some reason dont want to use jQuery.

like image 777
sushil bharwani Avatar asked Sep 08 '25 04:09

sushil bharwani


2 Answers

At the moment, the only way you can be sure to pick up every change in input contents straight away is to poll for it. This is because there are many possible ways an input can get edited without generating a keyup or immediate change event. As well as cut-and-paste there's drag-and-drop, undo/redo, autocomplete, spellchecker changes...

HTML5 proposes an input event that will fire in all cases like this, but browser support isn't there yet, unfortunately.

You can of course back up the polling with quicker checking for the common case where you do get an event. For example:

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';
});
like image 146
bobince Avatar answered Sep 10 '25 06:09

bobince


Handle the onblur event as well as the onkeyup event. Here is an example in 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>
like image 22
William Avatar answered Sep 10 '25 06:09

William