I have implemented auto complete search in my site. The problem is that response is coming properly but it do not iterate all elements in <ul><li>
elements. Always shows one element in HTML but coming multiple from response.
On the top search see if you type only river it comes with river records but do not show all in one ul li
means li
iteration is not working.
Here is my Jquery code:
<script>
$(document).ready(function(){
$('#keyword').keyup(function() {
var total;
$.ajax({
type: "POST",
url: "http://realtyexecutivesny.com/getRecSet.php?rnd=" + Math.random(),
data:{ key: $(this).val() },
success: function(data){
$.each(data.locations, function( key, value ) {
total = '<li>'+data.locations[0].value+'</li>';
});
$('#lists').html('<ul>'+total+'</ul>');
}
});
});
$('#lists ul li').click(function(){
$('#keyword').val($(this).html());
$('#field').val($(this).parent().data('field'));
});
});
</script>
Here is HTML Code:
<input type="text" name="keyword" id="keyword" />
<input type="hidden" name="field" id="field" value="all" />
<div id="lists"></div>
first Initialize total like
var total = '';
And in your each
, Use index
to get all records.
$.each(data.locations, function( index ) {
total += '<li>' + data.locations[index].value + '</li>';
});
$('#lists').html('<ul>' + total + '</ul>');
Try using .append()
it's a more clean approach.
success: function (data) {
$('#lists').html('<ul></ul>') // initiate clear element
$.each(data.locations, function (key, value) {
$('#lists ul').append('<li>' + data.locations[key].value + '</li>'); // append new elements to the ul element
});
}
Also check this: jquery .html() vs .append()
replace this:
total = '<li>'+data.locations[0].value+'</li>';
with this:
total += '<li>'+data.locations[0].value+'</li>';
and befor the each loop define total like below:
var total = '';
$.each(data.locations, function( key, value ) {
total += '<li>'+data.locations[0].value+'</li>';
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.