Javascript 使用文本填充某些字段时启用提交按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14632110/
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 17:26:06  来源:igfitidea点击:

Enable submit button when filling in some field with text

javascripthtmlformsbuttonsubmit

提问by samyb8

I have the following form and javascript:

我有以下表格和 javascript:

<script type="text/javascript">
function toggleButton(ref,bttnID){
  document.getElementById(bttnID).disabled= ((ref.value !== ref.defaultValue) ? false : true);
}
</script>

<form action="" method="post" id="subscribe" name="subscribe">
<label>NAME:</label>
<input type="text" name="name" class="subName" onkeyup="toggleButton(this,'bttnsubmit');">
<label>EMAIL:</label>
<input type="text" name="email" class="subEmail" id="sub_email">
<input type="button" name="button" value="Subscribe" disabled='disabled' id='bttnsubmit'/>
</form>

When I first load my site the SUBMIT button is disabled, as I wanted, since the text field has no text in it. Now I would like to enable the button once some text has been placed within the text field.

当我第一次加载我的网站时,提交按钮被禁用,正如我所希望的,因为文本字段中没有文本。现在我想在文本字段中放置一些文本后启用该按钮。

Any help please?

请问有什么帮助吗?

回答by technosaurus

The existing code in the question worked fine, but gets disabled when the text is removed. This may be desired by others but you could make a small change to have it permanently removed without needing jquery (jquery wasn't in the tags)

问题中的现有代码运行良好,但在删除文本时被禁用。这可能是其他人想要的,但您可以进行一些小的更改以在不需要 jquery 的情况下永久删除它(jquery 不在标签中)

function toggleButton(ref,bttnID){
  document.getElementById(bttnID).removeAttribute("disabled");
}

and add onkeyup="toggleButton(this,'bttnsubmit')to any fields that need to enable the button

并添加onkeyup="toggleButton(this,'bttnsubmit')到需要启用按钮的任何字段

回答by MikeB

Using jQuery:

使用jQuery:

$(document).ready(function() {
     $('#bttnsubmit').attr('disabled','disabled');
     $('input[type="text"]').keyup(function() {
        if($(this).val() != '') {
           $('input[type="submit"]').removeAttr('disabled');
        }
     });
 });

source: jQuery disable/enable submit button

来源:jQuery 禁用/启用提交按钮

回答by samyb8

Adding the final code that did the trick:

添加成功的最终代码:

<script type="text/javascript">
$(document).ready(function() {
     $('#bttnsubmit').attr('disabled','disabled');
     $('#subEmail').keyup(function() {
        if($(this).val() != '') {
           $('#bttnsubmit').removeAttr('disabled');
        }
        else {
        $('#bttnsubmit').attr('disabled','disabled');
        }
     });
 });
</script>