I've got a search box and a search button. I can hit the search button and the results pop up, no problem, works fine. I wanted to add the ability to search by pressing enter as well, so I added in some code to listen for the keypress and click my button when the keypress is released. This, however, results in the form being submitted and reloads the page with no data. I tried adding in preventDefault() and stopPropagation() to the event listener, but no matter what, the form gets submitted when I hit enter. It shows the correct information for a split second, but then immediately reloads the page.
Here's the HTML:
<script defer src="https://use.fontawesome.com/releases/v5.0.10/js/all.js" integrity="sha384-slN8GvtUJGnv6ca26v8EzVaR9DC58QEwsIk9q1QXdCU8Yu8ck/tL/5szYlBbqmS+" crossorigin="anonymous"></script>
<div class="container-fluid">
<div class="row search-box" id="firstRow">
<div class='col-10 search-head-two'>
<form class="form">
<input type="text" class="search-input" id="term">
</form>
</div>
<div class='col-2 search-head-one'>
<button id="search"><i class="fa fa-search"></i></button>
</div>
</div>
</div>
</div>
Here's the Javascript:
var content = [];
document.getElementById("term")
.addEventListener("keyup", function(event) {
event.stopPropagation();
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("search").click();
}
});
document.getElementById("search").onclick = function() {getData()};
function getData() {
var domain = "https://en.wikipedia.org/w/api.php?&origin=*&action=opensearch&search=" + encodeURI(document.getElementById('term').value) + "&limit=10";
fetch(domain).then(function(resp) {
return resp.json()
}).then(function(data) {
for (var i = 1; i < data.length; i++) {
content.push(data[i]);
}
var content1 = content[0];
var content2 = content[1];
var content3 = content[2];
for (var x = 0; x < content[0].length; x++) {
addRow(content1, content2, content3, x);
}
console.log(content[0]);
console.log(content[1]);
console.log(content[2]);
});
}
function addRow(content1, content2, content3, x) {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = '<div class="col-3" id="title">\
<p>' + content1[x] + '</p>\
</div>\
<div class="col-9" id="content">\
<p>' + content2[x] + '</br></br><a target="_blank" href="' + content3[x] + '">' + content3[x] + '</a></p>\
</div>';
document.getElementById('firstRow').appendChild(div);
}
Also important to note is that I'm using Bootstrap 4, Jquery and Jquery UI as external scripts. I'm running this in CodePen.io.
I moved the event.preventDefault() into the if clause, and changed the eventListener from keyup to keydown since the form was getting submitted on keydown not keyup. Now it works like a charm.
document.getElementById("term")
.addEventListener("keydown", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("search").click();
}
});