I'd like to implement a search box on my site. To be more specific, I want to invoke the search function when I hit enter key in the search box. The html code block I use:
<li class="search-box">
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" id="search-box" class="form-control" placeholder="Search...">
</div>
<button type="button" class="btn btn-default search-submit">Submit</button>
</form>
And the js code block:
function search() {
let query = $('input').val().trim();
console.log('query: ' + query);
window.location.href = '?query=' + query;
}
// this works.
$('.search-submit').on('click', function () {
search();
});
// this does not work ):
$('#search-box').keydown(function (e) {
if (e.keyCode === 13) {
search();
}
});
The query has been logged when I hit enter key, but the redirection does not succeed. Any hints?
Pressing enter attempts to submit the html form. That's the default behavior. Thus it will redirect to the same page since your form element does not contain the action
attribute. You can disable the form's default behavior by calling e.preventDefault()
.
Here's what you can do:
$('#search-box').keydown(function (e) {
if (e.keyCode === 13) {
e.preventDefault();
search();
}
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments