2013-10-21 30 views
0

我剛剛完成的代碼,允許我通過在搜索文本字段中輸入單詞來搜索來自mysql數據庫的產品信息,並且效果很好。 但是這個文本字段只在按下輸入時才起作用,而我想要更改爲像auto complete一樣的實時搜索。是可以更改爲jquery

我想改變爲jquery Keyup但不工作,請查看底部的代碼,看看是否有可能更改爲在文本字段上進行實時搜索!

<script type="text/javascript"> 

$(function() { 
//-------------- Update Button----------------- 


$(".search_button").click(function() { 
    var search_word = $("#search_box").val(); 
    var dataString = 'search_word='+ search_word; 

    if(search_word=='') 
    { 
    } 
    else 
    { 
    $.ajax({ 
    type: "GET", 
    url: "searchdata.php", 
    data: dataString, 
    cache: false, 
    beforeSend: function(html) { 

    document.getElementById("insert_search").innerHTML = ''; 
    $("#flash").show(); 
    $("#searchword").show(); 
    $(".searchword").html(search_word); 
    $("#flash").html('<img src="ajax-loader.gif" align="absmiddle">&nbsp;Loading Results...'); 



      }, 
    success: function(html){ 
    $("#insert_search").show(); 

    $("#insert_search").append(html); 
    $("#flash").hide(); 

    } 
}); 

    } 


    return false; 
    }); 



}); 
</script> 
+0

爲什麼重新發明輪子?看看[jQuery UI Autocomplete](http://jqueryui.com/autocomplete/)或[typeahead.js](http://twitter.github.io/typeahead.js/) – Phil

+1

試試$(「#search_box 「).keyup()而不是$(」。search_button「)。click() –

回答

2

你可以使用.keyup(),像

$("#search_box").keyup(function() { //keyup for #search_box input 
    var search_word = $(this).val(), 
     dataString = 'search_word='+ search_word; 
    ....rest of your code 
}); 
1

我發現代碼中的位是絕對可以得到改善。

首先要記住的是,每次用戶按下某個鍵時,它都會向服務器發起一個新的請求。讓我們這樣做...

// This will be our timer to stop the server being flooded by requests 
var searchDelay; 

// How many milliseconds should we wait before we search? 
var WAIT_TIME = 120; 

// This will be our search function 
function runSearch() { 
    // Grab the value from the input 
    var search_word = $("#search_box").val(); 

    // Stop empty answers 
    if (search_word == '') return; 

    // Show your result box 
    $("#insert_search").empty(); 
    $("#flash").html('<img src="ajax-loader.gif" align="absmiddle">&nbsp;Loading Results...').show(); 
    $("#searchword").show(); 
    $(".searchword").html(search_word); 

    // We can shortcut the $.ajax with a $.get too, which will do some encoding for the URL for us. 
    $.get('searchdata.php', {search_word: search_word}, function(data) { 
     $("#insert_search").append(html).show(); 
     $("#flash").hide(); 
    }).fail(function() { 
     // What happens if the server returns an error? 
     alert('Sorry, please try again later.'); 
     }); 
} 

// Now we can very easily bind our slick new function to different events! 
$('.search_button').on('click', runSearch); 

// And if the search box is typed into... 
$('#search_box').on('keyup', function() { 
    if (typeof(searchDelay) != 'undefined') clearTimeout(searchDelay); 
    searchDelay = setTimeout(runSearch, WAIT_TIME); 
});