Juan Juan - 25 days ago 10
Javascript Question

keypress event in jquery doesn't work well

I created a page where i search wikipedia articles. I want that the page search when i click the button search ,or when i press enter key inside the input form. The problem is that the enter key only works if i click first the button search.Why?

Page:http://codepen.io/Juan1417/pen/XNJeWd

$(document).ready(function(){

$("#searchTerm").keypress(function(e){

if(e.which==13) $("#search").click();

});

$("#search").click(function(){

var searchTerm=$("#searchTerm").val();

var url="https://en.wikipedia.org/w/api.php?action=opensearch&search="+searchTerm+"&format=json&callback=?";

$.ajax({

type:"GET",
url:url,
async:false,
dataType:"json",
success:function(data){

for(var i=0;i<data[1].length;i++){

$("#output").prepend("<li><a href="+data[3][i]+" target='_blank'>"+data[1][i]+"</a><br><span>"+data[3][i]+"</span><br>"+data[2][i]+"</p></li>");

}

},

error:function(errorMessage){

alert(errorMessage);

}

});

});

});

Answer

Seems like you aren't stopping the function to run after the enter (so the form is submitted).

if(e.which==13) {
  $("#search").click();
  e.stopPropagation();
  return false;
}
Comments