I have an async function which works only when I click on the search button, but I want the function to start also if I press the "enter" key on the keyboard.
Is this possible with Vanilla Javascript and async function?
I made several attempts, but it seems not to be working.
html
<input type="text" id="input-search" placeholder=""><span><button id="search-button">Search</button></span>
Js
let userName = document.querySelector('#username');
let button = document.querySelector('#search-button');
button.onclick = async function getData() {
let username = document.getElementById('input-search').value;
axios.get(`https://api.templatewebsite`)
.then(
async response => {
let data = await response.data
if (response.status !== 200) {
throw new Error(response.status);
} else {
console.log(data);
I tried to keep the code snippets short, to avoid unnecessary information.
CodePudding user response:
You have two options, first is to wrap it in <form>
component and handle this code on submit. Second is to add event listener on input and check if its enter:
userName.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
// Magic happens here
}
}
CodePudding user response:
Yes, you can do it like this:
let userName = document.querySelector('#username');
let button = document.querySelector('#search-button');
let input = document.querySelector('#input-search')
async function getData() {
// do some async actions
alert('getData called')
}
button.onclick = getData;
input.addEventListener('keyup', function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
getData();
}
})
<input type="text" id="input-search" placeholder=""><span><button id="search-button">Search</button></span>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
I tried to put the code suggested by @Shamloo and tried to adapt it to my code. It throws an error when it tries to grab the value of the input field, after the axios API call.
Probably I put the code in the wrong place, because it throws an error even if the input field contains the right value.
I did like this:
let input = document.querySelector('#input-search')
async function getData(){
document.querySelector('#input-search').value
//API CALL with axios
axios.get(`https://api.webtemplate{input}`)
.then(
async response => {
let data = await response.data
//if the request can't be processed (data is not found)
if (response.status !== 200) {
throw new Error(response.status);
} else {
//request works, data is found
console.log(data)
outside of the function, at the bottom of the code
button.onclick = getData;
input.addEventListener('keyup', function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
getData();
}
})