views:

29

answers:

3

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.

A: 

Write the same code (that you have written on keyup event) on blur event.

See this answer http://stackoverflow.com/questions/3053523/disallow-typing-of-few-of-characters-e-g-in-all-input-textboxes-using-jq/3053661#3053661

In that answer it was done using jQuery and the purpose was different, but you can also do what you need without using jQuery.

Ismail
ismail please look my comments to Wduffy. Your answer wont help me in current scenario.
sushil bharwani
A: 

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>
WDuffy
on blur executes only when i have my focus outside the textarea. Consider a scenario when i load my form my button is disabled.Then i start typing in my button becomes enabled while typing. Now i with the mouse select all the text and cut the text my focus is still on the textarea which is empty but my button looks enabled.
sushil bharwani
A: 

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';
});
bobince