2014-08-27 31 views
0

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

问题是如果表单在搜索字段中加载了文本,我仍然必须使用空格或退格或类型以启用提交按钮。

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

这里是一个小提琴:http://jsfiddle.net/sz6aLjoz/

形式:

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

JQuery的:

$(function() { 
    $('#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); 
     } 
    }); 
}); 

回答

2

添加呼叫你的代码的最后触发.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(); 

jsFiddle example

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

+1

啊..感谢奏效..:d ...这就是我的回答 – user2912702 2014-08-27 15:29:16

+0

哇,这是有趣的。你能解释为什么这个工作吗? – nothing9 2014-08-27 15:32:01

+1

@ nothing9 - 我们在这里所做的只是在末尾添加'.keyup()',它只是触发键盘事件。这相当于添加'.trigger('keyup')'。 – j08691 2014-08-27 15:37:42

0

这是因为您开始使用禁用的按钮,就可以从按钮移除已停用的属性,并添加您准备函数内部此行

$('.enableOnInput').prop('disabled', $('#searchInput').val() == '');

小提琴here

0

如果绑定的输入通过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); 
     } 
    }); 
}); 

所以,现在,如果用户具有自动填充的,或以前搜索的东西,然后双击输入上的选择一个值,该代码将检查“#searchInput”的价值 - 所以;如果用户粘贴,如果有键盘事件或值发生变化,bind()中的代码将会运行。

这里的JSFiddle