I'd like to convert a search result received from server to unordered list:
function searchSuccess(json, textStatus, jqXHR) {
console.log('json is:', json);
var html= "<ul>";
Object.keys(json).forEach(function(key, val) {
html += "<li><a href=\'" + val['slug'] + "\'>" + val['title'] +"</a></li>";
});
html +="</ul>"
$('#search-results').append(html);
}
The json, as I see in the console is like:
json is: [{"title":"Hello World","slug":"hello-world"},{"title":"I'm a title","slug":"I-am-title"}]
However, instead of the linked li
, a list of undefined
is rendered.
What is wrong here? How can I fix it?
You had an array list with javascript object in your json. These codes works:
var json = '[{"title":"Hello World","slug":"hello-world"},{"title":"I\'m a title","slug":"I-am-title"}]';
function searchSuccess(json) {
console.log('json is:', json);
var html= "<ul>";
jsonObject = JSON.parse(json);
jsonObject.forEach(function(searchresult) {
html += "<li><a href=\'" + searchresult.slug + "\'>" + searchresult.title +"</a></li>";
});
html +="</ul>"
$('#search-results').empty().append(html);
}
searchSuccess(json);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="search-results"></div>
var json = '[{"title":"Hello World","slug":"hello-world"},{"title":"I\'m a title","slug":"I-am-title"}]';
function searchSuccess(json) {
var $ul = $('<ul>');
jsonObject = JSON.parse(json);
jsonObject.forEach(function(searchresult) {
var $li = $('<li>');
var $a = $('<a>');
$a.attr('href', searchresult.slug)
$a.text(searchresult.title);
$li.append($a);
$ul.append($li);
});
$('#search-results').empty().append($ul);
}
searchSuccess(json);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="search-results"></div>
This fixes
undefined
, but the problem is that it append ANYTHING that comes from the server after each key up. Is there any way to filter out only for the latest searchresult?Or if you want to clear the div before appending new you can replace
$('#search-results').append(html)
with$('#search-results').empty().append(html)
Thanks Mark, but this still adds up to results. What I mean is to eliminate the previous (irrelevant) result sets, and show the latest set which matches the search term. The function that sends out values is here: stackoverflow.com/questions/56868810 /form-input-field-not-recognized-in-jquery
Added my answer again, added the
empty()
function to clear the div before appending new content.