2014-08-27 30 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