如果用户填写输入框,则启用按钮,如果用户已清空或未填写,则禁用

时间:2015-06-19 03:19:58

标签: javascript jquery

我希望在用户填写或在输入框中键入内容时启用该按钮,如果用户未填写或清空输入框,则禁用该按钮。可悲的是,我的下面的片段无法正常工作。非常感谢任何帮助,建议,推荐,想法和线索。



$(document).ready(function(){
  $("input").keypress(function(){
    if($(this).val() !== ""){
      //user fill or did type something on the input search box, lets enable the button
      $("button").attr("disabled", false);
    }else if($(this).val() === ""){
      //user not fill or emptied the box, lets disabled the button
      $("button").attr("disabled", true);
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="search_input" value="" placeholder="Type your search here" />
<button disabled>Go</button>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:1)

好像你错过了大括号。现在就工作。

$(document).ready(function() {
  $("input").keyup(function() {
      if ($(this).val() !== "") {
        //user fill or did type something on the input search box, lets enable the button
        $("button").prop("disabled", false);
      } else if ($(this).val() === "") {
        //user not fill or emptied the box, lets disabled the button
        $("button").prop("disabled", true);

      }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="search_input" value="" placeholder="Type your search here" />
<button disabled>Go</button>

答案 1 :(得分:1)

您可以使用prop()函数将disabled属性设置为true / false。

$(document).ready(function() {
  $("input").keyup(function() {
      $("button").prop('disabled',$(this).val().length <= 0 );
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="search_input" value="" placeholder="Type your search here" />
<button disabled>Go</button>

答案 2 :(得分:1)

尝试使用inputfocus个活动,input input.length 0不大于input时进行关注。

注意,如果$(document).ready(function(){ $("input").on("input focus", function(){ if ($(this).val().length > 0) { //user fill or did type something on the input search box, lets enable the button $("button").prop("disabled", false); } else { //user not fill or emptied the box, lets disabled the button $("button").prop("disabled", true); } }); });值为多个空格字符,则不确定预期结果吗?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="search_input" value="" placeholder="Type your search here" />
<button disabled>Go</button>
$(document).ready(function(){
  $("input").keyup(function(){
      if ($(this).val().length > 0){
          $("button").attr("disabled", false);
      }
      else {
          $("button").attr("disabled", true);
      }
  });
});

答案 3 :(得分:1)

这很好......

ms-word:ofe|u|
  

http://jsfiddle.net/nhf52ceh/