I'm currently working on a wiki search project, and I've been met with a problem that I haven't been able to find an answer for on stackoverflow. I'm trying to execute a XMLHttp request when the enter key is pressed, but I haven't been able to get it to work. It always refreshes the page even though I've tried keyup, keydown, submit,and the bind method.
HTML code:
<form class="form-search ngen-search-form" action="" method "get">
<input type="text"name="q"id = "search-input"class="form-search
input"placeholder="Search keywords..."dir="ltr">
<span class="glyphicon glyphicon-search form-search-submit"
id="search-trigger"aria-hidden="true"></span>
</form>
JS code:
$(document).ready(function(){
//clicking search button expands search bar
$('#search-trigger').on('click',function(e){
e.preventDefault();
if(!$('#search-input').hasClass("search-input-open")){
$('#search-input').addClass('search-input-open');
}else{
send();
}
});
//--problem here-- enter button refreshes page instead of executing js
$("#search-input").keyup(function (e) {
if(e.keyCode==13){
console.log('works');
send();
}
});
//click away from search form causes search bar to close
$(document).on('click', function(e) {
e.preventDefault();
if(!$(e.target).is('#search-trigger')&&!$(e.target).is('#search-input')) {
$('#search-input').removeClass('search-input-open');
}
});
//request function to wikipedia API
function send(){
var xhr = new XMLHttpRequest();
//add precautionary if nothing entered
var searchTerm = document.getElementById('search-input').value;
var string = "http://en.wikipedia.org/w/api.php?action=opensearch&origin=*&search=" + searchTerm + "&formatversion=2&format=json";
xhr.open('GET',string);
xhr.onload = function(){
console.log(xhr.responseText);
};
xhr.send();
}
});