Javascript 每当文本字段为空时动态禁用按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7067005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:41:42  来源:igfitidea点击:

Disable button whenever a text field is empty dynamically

javascripthtmlbutton

提问by Eng.Fouad

Here's my code:

这是我的代码:

<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/>

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?

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

采纳答案by yoozer8

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.

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

Example:

例子:

<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>

回答by Harish Kulkarni

Easiest way to do it :-

最简单的方法:-

Simple Html and JavaScript : Run the snippet (Just 7 lines)

简单的 Html 和 JavaScript:运行代码片段(仅 7 行)

function success() {
  if(document.getElementById("textsend").value==="") { 
            document.getElementById('button').disabled = true; 
        } else { 
            document.getElementById('button').disabled = false;
        }
    }
<textarea class="input" id="textsend" onkeyup="success()" name="demo" placeholder="Enter your Message..."></textarea>
<button type="submit" id="button" disabled>Send</button>

I have used textarea, but you can use any html input tags and try it out! Happy coding!

我使用过 textarea,但您可以使用任何 html 输入标签并尝试一下!快乐编码!

回答by Spycho

You could poll the value of the input. This would be less efficient and less responsive but potentially more reliable.

您可以轮询输入的值。这会降低效率和响应速度,但可能更可靠。

As you pointed out, the keyup event won't neccessarily fire when an input's value is cleared. What if they highlight the text with the mouse, right click and cut?

正如您所指出的,当输入的值被清除时,keyup 事件不一定会触发。如果他们用鼠标突出显示文本,右键单击并剪切怎么办?

The change event might help, but it's still not all that reliable. It only fires on blur, and misses some changes (like an autocompletion selection).

change 事件可能会有所帮助,但它仍然不是那么可靠。它仅在模糊时触发,并且会错过一些更改(例如自动完成选择)。

Here's a jsFiddledemonstrating the polling solution.

这是一个演示轮询解决方案的 jsFiddle



In response to Eng.Fouad's comment, here's how to add the JS:

为了回应 Eng.Fouad 的评论,这里是如何添加 JS:

You could put it in a script tag, like this:

你可以把它放在一个脚本标签中,像这样:

<script type="text/javascript">
    //my code
</script>

That will work, but it will mean that your user's browser won't cache the JavaScript, meaning it will take longer to load your page. It's also cleaner to separate your scripts from your content. But if you want a quick and easy option, this should do. Put this at the bottom of your body and wrap it in a dom ready handler (see the bottom part of the answer).

这会起作用,但这意味着您用户的浏览器不会缓存 JavaScript,这意味着加载您的页面需要更长的时间。将脚本与内容分开也更清晰。但是如果你想要一个快速简单的选择,这应该可以。把它放在你身体的底部,然后把它包在一个 dom ready 处理程序中(见答案的底部)。

As a cleaner option, you can put it in an external file e.g. someScript.js, the contents of which would be your JavaScript (with no script tags). You then link to that script from your HTML file:

作为一个更简洁的选择,您可以将它放在一个外部文件中,例如 someScript.js,其内容将是您的 JavaScript(没有脚本标签)。然后从 HTML 文件链接到该脚本:

<html>
    <head></head>
    <body>
        <!-- contents of page -->
        <script type="text/javascript" src="/path/to/someScript.js"></script>
    </body>
</html>

NB: You need to make your script web accessible so that browsing to http://www.your-site.com/path/to/someScript.jsaccesses the script.

注意:您需要使您的脚本网络可访问,以便浏览http://www.your-site.com/path/to/someScript.js访问脚本。

The script tag is at the bottom of the body so that the page loads the actual content first, and the scripts afterwards. This will mean that your content is visible to your users sooner.

script 标签位于正文的底部,因此页面首先加载实际内容,然后加载脚本。这意味着您的内容可以更快地对您的用户可见。



You should make one last modification to the JavaScript in the jsFiddle. The jsFiddle has the code running "onDomReady" (see top left of the fiddle). Technically, you don't need to do this if you have your script after your content. It's there to ensure that the script runs after the content has loaded, so that if the script attempts to find elements in the DOM, they have been loaded, and are found. You should probably add this to the script in case (for some reason) you move the script to before the content. In order to wrap your script in a dom ready handler in jQuery, do this:

您应该对 jsFiddle 中的 JavaScript 进行最后一次修改。jsFiddle 有运行“onDomReady”的代码(见小提琴的左上角)。从技术上讲,如果您在内容之后拥有脚本,则无需执行此操作。它用于确保脚本在内容加载后运行,以便如果脚本尝试在 DOM 中查找元素,则它们已被加载并被找到。您可能应该将此添加到脚本中,以防(出于某种原因)您将脚本移动到内容之前。为了将您的脚本包装在 jQuery 中的 dom 就绪处理程序中,请执行以下操作:

$(function(){
    //my code
});

In that example, code put where the //my codecomment is will be run only when the page is ready.

在该示例中,//my code仅当页面准备就绪时,才会运行放置在注释位置的代码。

回答by Gaurav KR

 <input type="number" id="abc" onkeyup="s()">
 <input type="submit" id="abc2" disabled >
<script type="text/javascript">
function s(){
var i=document.getElementById("abc");
if(i.value=="")
    {
    document.getElementById("abc2").disabled=true;
    }
else
    document.getElementById("abc2").disabled=false;}</script>

回答by abhinand

Here button is disabled by default and when keyup event is triggered, check if text field value is length is zero or not. If zero then button is disabled, else enabled.

默认情况下禁用此处按钮,当触发 keyup 事件时,检查文本字段值的长度是否为零。如果为零,则按钮被禁用,否则启用。

<head>
    <title>Testing...</title>
</head>

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

    <script type="text/javascript">


        function btnActivation(){

            if(!document.getElementById('myText').value.length){
                document.getElementById("start_button").disabled = true;            
            }else{
                document.getElementById("start_button").disabled = false;

            }           
        }   

    </script>
</body>