我使用jquery和WordPress函数创建了一个自动提示列表。我的autosuggestion工作正常。我在这里给我的代码
Jquery代码
(function ($) {
$(document).ready(function () {
$('#my_ajax').autocomplete({
// minChars: 1,
source: function(request, response) {
$.ajax({
type: 'POST',
dataType: 'json',
url: devel_ajax.ajaxurl,
data: 'action=my_ajax'+'&name='+request.term,
success: function(data) {
response( $.map( data, function( item ) {
return {
label: item.title,
value: item.title
}
}));
}
});
},
minLength: 3,
});
})(jQuery);
PHP代码
function user_autocomplete($value){
global $wpdb;
$name = $wpdb->esc_like(stripslashes($value));
$users = $wpdb->get_results("SELECT DISTINCT
$wpdb->users.ID
FROM $wpdb->users
WHERE LOWER($wpdb->users.user_login) LIKE LOWER('".$name."%')");
$autocomplete = array();
foreach($users as $key => $user){
$user_info = get_userdata($user->ID);
$firstname = $user_info->first_name;
$lastname = $user_info->last_name;
if(!empty($firstname) || !empty($lastname)){
$username = ucfirst($firstname) . ' '. ucfirst($lastname);
}else{
$username = $user_info->user_login;
}
$email = $user_info->user_login;
$website = $user_info->website;
$autocomplete[$user->ID] = array(
'ID' => $user->ID,
'Name' => $username
'email' => $email
'website' => $website
);
}
return $autocomplete;
}
HTML代码
<form action='' method='POST' role="form" class="bottom-space">
<div class="form-group">
<input id="my_ajax" autofocus="" value="" type="text" name="q" placeholder="my_ajax" style="width:100%;max-width:600px;outline:0" autocomplete="off">
<input id="firstname" name="firstname" type="hidden" value=''>
<input id="lastname" name="lastname" type="hidden" value=''>
<input id="id" name="user_id" type="hidden" value=''>
<input id="email" name="email" type="hidden" value=''>
<input id="website" name="email" type="hidden" value=''>
</div>
<submit type="submit" class="btn btn-default">Submit
Button</submit>
</form>
但问题是我无法设置其他隐藏的输入字段。任何形式的帮助或建议都非常值得赞赏。
答案 0 :(得分:4)
代码未经过测试。但我认为这对你有用。我给你一些代码片段。
(function ($) {
$(document).ready(function () {
$('#my_ajax').autocomplete({
// minChars: 1,
source: function(request, response) {
$.ajax({
type: 'POST',
dataType: 'json',
url: devel_ajax.ajaxurl,
data: 'action=my_ajax'+'&name='+request.term,
success: function(data) {
response( $.map( data, function( item ) {
var object = new Object();
object.label = item.Name;
object.value = item.Name;
object.ID = item.ID;
object.email = item.email;
object.website = item.website;
return object
}));
// response( $.map( data, function( item ) {
// return {
// label: item.title,
// value: item.title
// }
// }));
}
});
},
select: function (event, ui) {
$("#my_ajax").val(ui.item.value);
$("#firstname").val(ui.item.value);
$("#id").val(ui.item.ID);
$("#email").val(ui.item.email);
$("#website").val(ui.item.website);
}
});
});
})(jQuery);