每当文本字段为空时动态禁用按钮 [英] Disable button whenever a text field is empty dynamically

查看:33
本文介绍了每当文本字段为空时动态禁用按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

<input type="text" onkeyup="if(this.value.length > 0) document.getElementById('start_button').disabled = false; else document.getElementById('start_button').disabled = true;"/>
<input type="button" value="Click to begin!" id="start_button" disabled/>

这有效但仍然没有效率,因为用户可以删除文本框中的文本并在按住 DELETE 键的同时单击按钮.使用 javascript 有没有更有效的方法来实现这一点?

This works but still not efficient since the user can delete the text inside the text box and click the button while he's holding on DELETE key. Is there a more efficient way to achieve this using javascript?

推荐答案

添加点击按钮时检查是否有任何文本.如果没有,弹出一个警告框(或其他形式的反馈),告诉用户输入数据,不要执行按钮功能.

Add a check when the button is clicked to see if there is any text. If there isn't, pop up an alert box (or some other form of feedback) to tell the user to enter data, and don't do the button functionality.

示例:

<input id="myText" type="text" onkeyup="stoppedTyping()">
<input type="button" value="Click to begin!" id="start_button" onclick="verify()" disabled/> 

<script type="text/javascript">
    function stoppedTyping(){
        if(this.value.length > 0) { 
            document.getElementById('start_button').disabled = false; 
        } else { 
            document.getElementById('start_button').disabled = true;
        }
    }
    function verify(){
        if myText is empty{
            alert "Put some text in there!"
            return
        }
        else{
            do button functionality
        }
    }
</script>

这篇关于每当文本字段为空时动态禁用按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆