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