我知道這個問題以前已經被問過,但是我找不到任何答案是最新的或功能的(至少對於我的應用程序來說)。使用JQuery自動完成的力選擇
我的JQuery自動完成框使用mysql數據庫作爲其源。我希望用戶能夠鍵入以獲得推薦,但是在提交表單之前被迫從下拉選擇中進行選擇。
我的javascript:
<script type="text/javascript">
$.widget('ui.autocomplete', $.ui.autocomplete, {
_renderMenu: function(ul, items) {
var that = this;
$.ui.autocomplete.currentItems = items;
$.each(items, function(index, item) {
that._renderItemData(ul, item);
});
}
});
$.ui.autocomplete.currentItems = [];
$(function() {
$("#college").autocomplete({
source: "search.php",
minLength: 5
});
});
var inputs = {college: false};
$('#college').change(function(){
var id = this.id;
inputs[id] = false;
var length = $.ui.autocomplete.currentItems.length;
for(var i=0; i<length; i++){
if($(this).val() == $.ui.autocomplete.currentItems[i].value){
inputs[id] = true;
}
}
});
$('#submit').click(function(){
for(input in inputs){
if(inputs.hasOwnProperty(input) && inputs[input] == false){
alert('incorrect');
return false;
}
}
alert('correct');
$('#college_select_form').submit();
});
</script>
我的形式:
<form action="choose.php" method="post" id="college_select_form" name="college_select_form">
<input type="text" id="college" name="college" class="entry_field" value="Type your school" onclick="this.value='';" onfocus="this.select()" onblur="this.value=!this.value?'Type your school':this.value;" /><input type="submit" id="submit" name="submit" class="submitButton" value="Go" title="Click to select school" />
</form>
的search.php:
<?php
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e) {
echo $e->getMessage();
}
$return_arr = array();
if ($conn)
{
$ac_term = "%".$_GET['term']."%";
$query = "SELECT * FROM college_list where name like :term";
$result = $conn->prepare($query);
$result->bindValue(":term",$ac_term);
$result->execute();
/* Retrieve and store in array the results of the query.*/
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
array_push($return_arr, array('label' => $row['name'], 'value' => $row['name']));
}
}
/* Free connection resources. */
//$conn = null;
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
?>
那麼,什麼將是這樣做的最佳方法?我能想到的唯一解決方案是使用PHP來驗證文本框的值是否與數據庫中的值匹配,但我不確定如何使用當前的代碼實現該值。
請參閱我的更新。 – Aust
替換:'$('#college_select_form')。submit();' With:'if($('#college').length> 0){$('#college_select_form')。submit();} else {alert('你必須選擇一所學校!');}' 你應該看看:http://docs.jquery.com/Plugins/Validation – DevlshOne