Reputation: 45
I have a search bar where if I type anything it processes the answer or the output in another Modal. and then, if I click [search] button, then the modal triggers. Now I want that if I press enter inside the box, it will trigger the button.
<form class="form-inline" >
<input class="form-control mr-sm-1" onkeyup="SearchFunction()" id="searchinputfeild"
type="search" placeholder="" aria-label="Search">
<a class="btn btn-outline-success my-2 my-sm-0" id="searchbutton" data-toggle="modal" data-
target="#resultsModal">Search</a>
</form>
I am very very weak at javascript. please give me suggestions on how can I make it possible.
Upvotes: 3
Views: 45
Reputation: 347
Hi, you can do this by simple JavaScript Code:
Your HTML (some changes):
<form class="form-inline" >
<input class="form-control mr-sm-1" id="searchinputfeild" type="search" placeholder="" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" id="searchbutton" data-toggle="modal" data-target="#resultsModal">Search</button>
</form>
Don't use < a > tag, instead use button.
Now Finally Place following JavaScript code below in your body (or anywhere):
<script>
var input = document.getElementById("searchinputfeild");
input.addEventListener("keyup", function (event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchbutton").click();
}
});
</script>
YOU ARE DONE.
It Will work smoothly 👍
If you wanna Test, Check it below by running alert test snippet:
var input = document.getElementById("searchinputfeild");
input.addEventListener("keyup", function (event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchbutton").click();
}
});
<form class="form-inline" >
<input class="form-control mr-sm-1" id="searchinputfeild" type="search" placeholder="" aria-label="Search">
<button onclick="javascript:alert('Hey Congrats! I am working.')" class="btn btn-outline-success my-2 my-sm-0" id="searchbutton" data-toggle="modal" data-target="#resultsModal">Search</button>
</form>
Upvotes: 1
Reputation: 537
<form class="form-inline" id="myForm">
<input class="form-control mr-sm-1" id="searchinputfeild"
type="search" placeholder="" aria-label="Search">
<a class="btn btn-outline-success my-2 my-sm-0" id="searchbutton" data-toggle="modal" data-
target="#resultsModal">Search</a>
</form>
<script type="text/javascript">
var form = document.getElementById("myForm");
function handleForm(event) { event.preventDefault(); }
form.addEventListener('submit', submit);
function submit(event) {
event.preventDefault()
console.log('code here')
}
</script>
Upvotes: 1