snow snow - 1 year ago 73
Javascript Question

appendTo shows strange behaviour

What I am trying to do (for now) is query the Wikipedia API with a search string,

$(document).ready(function() {
$(".search").on("click", getArticles);

function getArticles() {
var searchTerm = $("#wiki-search").val().trim();
var url = "";
$.getJSON(url, {
action: "query",
format: "json",
list: "search",
srprop: "snippet",
srlimit: 10,
srsearch: searchTerm
}, displayArticles);

and from the returned JSON object, display the value of a particular property (
in this case) by appending it to a div element:

function displayArticles(wikiJSON) {
if(wikiJSON.query.searchinfo.totalhits === 0) {
// resultsDiv.innerHTML = "No results found";
$("<h3>No results Found</h3>").appendTo("#resultsID");
else {

But as seen in this pen, the snippet value is flashed momentarily on the screen and is gone. Could anyone please explain what's going wrong with my code?


<form role="form">
<div class="input-group">
<input class="form-control" id="wiki-search" type="text" placeholder="Enter search string...">
<span class="input-group-btn">
<button class = "btn btn-default search">
<i class = "glyphicon glyphicon-search"></i>
<span class="input-group-btn">
<button class = "btn btn-default random">
<i class = "glyphicon glyphicon-random"></i>
<div class= "row result-group">
<div class = "col-xs-12 col-sm-8 col-sm-offest-2 col-md-6 col-md-offset-3">
<div class = "results" id = "resultsID">


Answer Source

There are two issues.

First, your button is implicitly submitting the form (its default type is submit).

So you need to add type="button" to your button elements.

Secondly, the returned html cannot be sent to the jQuery constructor because it is not syntactically correct according to the jQuery constructor. There is a logged error message: "Uncaught Error: Syntax error, unrecognized expression". The result should be sent to the .html() function.


Working pen

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download