问题
I am getting an error in this code. Can anybody help me?
<h4>search:<input type="text" id="name-list" /></h4>
<script type="text/javascript" language="javascript">
$(function () {
$("#name-list")
.autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/Searchuser", type: "POST", dataType: "json",
data: { searchText: request.term, maxResults: 10 }
})
return false;
},
minLength: 1
}).data("autocomplete")._renderItem = function (ul, item) {
var inner_html = '<a><div class="list_item_container"><div class="image"><img src="' + item.PicLocation + '"></div><div class="label">' + item.label + '</div><div class="description">' + item.DisplayName + '</div></div></a>';
return $("<li></li>")
.data("item.autocomplete", item)
.append(inner_html)
.appendTo(ul);
};
});
</script>
The data is receiving correctly from the server. Where have i made mistake?
回答1:
@ JoeFletch Thanks for your help.
I made these changes to the code and then it worked well. Here are some css i used.
<style type="text/css">
DIV.list_item_container {
height: 90px;
padding: 0px;
}
DIV.image {
width:90px;
height: 90px;
float: left;
}
DIV.description {
font-style: italic;
font-size: 1.1em;
color: gray;
padding: 5px;
margin: 5px;
}
#name-list
{
width: 300px;
}
</style>
Here is my script
$(document).ready(function () {
$('#name-list').autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/Searchuser",
data: { searchText: request.term, maxResults: 10 },
dataType: "json",
success: function (data) {
response($.map(data, function (item) {
return {
value: item.DisplayName,
avatar: item.PicLocation,
rep: item.Reputation,
selectedId: item.UserUniqueid
};
}))
}
})
},
select: function (event, ui) {
alert(ui.item ? ("You picked '" + ui.item.label)
: "Nothing selected, input was " + this.value);
return false;
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
var inner_html = '<a><div class="list_item_container"><div class="image"><img src="' + item.avatar + '"></div><div class="label"><h3> Reputation: ' + item.rep + '</h3></div><div class="description">' + item.label + '</div></div></a><hr/>';
return $("<li></li>")
.data("ui-autocomplete-item", item)
.append(inner_html)
.appendTo(ul);
};
});
Thanks @Joe. I updated the answer.
回答2:
For anyone looking at this again. The code provided by mjmrz is fantastic, but only up to jQuery UI 1.8.
After that .data("autocomplete")
needs to be changed to .data("ui-autocomplete")
and .data("item.autocomplete"
, item) needs to be changed to b .data("ui-autocomplete-item", item)
.
Otherwise, no images. Hope this helps someone else.
来源:https://stackoverflow.com/questions/12670956/jquery-ui-autocomplete-with-image