开发者

textarea empty should show disabled button

开发者 https://www.devze.com 2023-01-16 18:38 出处:网络
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 texta

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.


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


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>


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

See this answer Disallow typing of few of characters e.g.'<', '>' in all input textboxes using jquery

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号