Javascript jQuery禁用搜索输入不工作

Javascript jQuery禁用搜索输入不工作,javascript,jquery,html,Javascript,Jquery,Html,我有一个搜索输入,它执行以下操作。 如果搜索字段为空,则按钮被禁用(此操作正常) 问题是,如果表单在搜索字段中加载了文本,我仍然必须使用空格、退格或键入来启用submit按钮 如果加载表单时搜索字段中有值,我希望启用提交按钮 这是一把小提琴: 表格: <form> <input type="text" name="dosearch" id="searchInput" value="test" class="form-control" placeholder="Searc

我有一个搜索输入,它执行以下操作。 如果搜索字段为空,则按钮被禁用(此操作正常)

问题是,如果表单在搜索字段中加载了文本,我仍然必须使用空格、退格或键入来启用submit按钮

如果加载表单时搜索字段中有值,我希望启用提交按钮

这是一把小提琴:

表格:

<form>
    <input type="text" name="dosearch" id="searchInput" value="test" class="form-control" placeholder="Search...">
    <button name="submit" class="enableOnInput" id="submitBtn" disabled='disabled' type="submit">Search</button>
</form>

在代码末尾添加对触发器
.keyup()
的调用:

$('#searchInput').keyup(function () {
    if ($(this).val() == '') { //Check to see if there is any text entered
        //If there is no text within the input ten disable the button
        $('.enableOnInput').prop('disabled', true);
    } else {
        //If there is text in the input, then enable the button
        $('.enableOnInput').prop('disabled', false);
    }
}).keyup();


这样,当页面加载时,事件将被触发,就好像用户按了一个键,您的代码被执行一样。

这是因为您从禁用按钮开始,您可以从按钮中删除禁用属性,并在就绪函数中添加这一行

$('.enableOnInput').prop('disabled',$('searchInput').val()


Fiddle

如果您通过JQuery绑定输入,它将自动检测对“#searchInput”值的任何更改。下面是JavaScript:

$(function () {
    $("#searchInput").bind("change paste keyup", function() {
        if ($(this).val() == '') { //Check to see if there is any text entered
            //If there is no text within the input ten disable the button
            $('.enableOnInput').prop('disabled', true);
        } else {
            //If there is text in the input, then enable the button
            $('.enableOnInput').prop('disabled', false);
        }
    });
});
因此,现在,如果用户打开了autofill,或者之前搜索过某个内容,然后双击输入选择一个值,代码将检查“#searchInput”的值;如果用户粘贴,如果有keyup事件或值更改,则将运行
bind()
中的代码


这里是

@nothing9-我们在这里所做的就是在末尾添加
.keyup()
,这只会触发keyup事件。这相当于添加
.trigger('keyup')
$(function () {
    $("#searchInput").bind("change paste keyup", function() {
        if ($(this).val() == '') { //Check to see if there is any text entered
            //If there is no text within the input ten disable the button
            $('.enableOnInput').prop('disabled', true);
        } else {
            //If there is text in the input, then enable the button
            $('.enableOnInput').prop('disabled', false);
        }
    });
});