gpt4 book ai didi

javascript - jQuery 自动完成 - 传递值而不是名称

转载 作者:行者123 更新时间:2023-12-03 09:22:04 24 4
gpt4 key购买 nike

我有一个使用以下方法的自动完成功能。我输入后,它会返回我正在搜索的个人的用户名,如果我愿意的话,它还会显示该用户的 ID。但是,我需要的是在输入框中显示名字和姓氏,但在提交表单时传递实际值(ID)。那么如何获取输入类型的值作为 ID,但将下拉列表显示为名字和姓氏呢?

HTML

<input type='search' id='nameSearch' placeholder='Search User' />

脚本

<script>
$(document).ready(function(){

$('#nameSearch').autocomplete({

source:'results.php',
minLength:1,
select: function(event, ui){

// just in case you want to see the ID
var accountVal = ui.item.value;
console.log(accountVal);

// now set the label in the textbox
var accountText = ui.item.label;
$('#nameSearch').val(accountText);

return false;
},
focus: function( event, ui ) {
// this is to prevent showing an ID in the textbox instead of name
// when the user tries to select using the up/down arrow of his keyboard
$( "#nameSearch" ).val( ui.item.label );
return false;
},

});

});
</script>

SQL

include "libs/db_connect.php";

// get the search term
$search_term = isset($_REQUEST['term']) ? $_REQUEST['term'] : "";

// write your query to search for data
$query = "SELECT
ID, NAME, LAST_NAME
FROM
b_user
WHERE
NAME LIKE \"%{$search_term}%\" OR
LAST_NAME LIKE \"%{$search_term}%\"
LIMIT 0,10";

$stmt = $con->prepare( $query );
$stmt->execute();

// get the number of records returned
$num = $stmt->rowCount();

if($num>0){

// this array will become JSON later
$data = array();

// loop through the returned data
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);

$data[] = array(
'label' => $NAME . " " . $LAST_NAME,
'value' => $ID
);
}

// convert the array to JSON
echo json_encode($data);

}

//if no records found, display nothing
else{
die();
}

最佳答案

这样的东西有用吗?

HTML

<input type='search' id='nameSearch' placeholder='Search User' />
<input type='hidden' id='nameSearchID' />

脚本

<script>
$(document).ready(function(){

$('#nameSearch').autocomplete({

source:'results.php',
minLength:1,
select: function(event, ui){

// set the value of the ID
var accountVal = ui.item.value;
$('#nameSearchID').val(accountVal);

// now set the label in the textbox
var accountText = ui.item.label;
$('#nameSearch').val(accountText);

return false;
},
focus: function( event, ui ) {
// this is to prevent showing an ID in the textbox instead of name
// when the user tries to select using the up/down arrow of his keyboard
$('#nameSearch').val( ui.item.label );
$('#nameSearchID').val( ui.item.value );
return false;
},

});

});
</script>

关于javascript - jQuery 自动完成 - 传递值而不是名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31812006/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com