How to simulate the Enter button to replicate the submit button? - javascript

I am making a weather application with a textarea, if you click "submit" you will see the weather results. Now, I want to make it so you can click enter to see the data. this is some code:
<section class="inputs">
<input type="text" placeholder="Enter any city..." id="cityinput">
<input type="submit" value="Submit" id="add">
<button placeholder="submit" id="add"></button>
</section>
This is some javascript code:
btn.addEventListener('click', function(){
//This is the api link from where all the information will be collected
fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputval.value+'&appid='+apik)
.then(res => res.json())
//.then(data => console.log(data))
.then(data => {
//Now you need to collect the necessary information with the API link. Now I will collect that information and store it in different constants.
var nameval = data['name']
var tempature = data['hourly']['pop']
//Now with the help of innerHTML you have to make arrangements to display all the information in the webpage.
city.innerHTML=`Weather of <span>${nameval}<span>`
temp.innerHTML = ` <span>${ tempature} </span>`
})

You need to attach a listener to your textarea, if the user press enter then you execute your call (here simulated by an alert) and you prevent the default in order to don't go in a new line. In any other case, just don't take any action
const textArea = document.querySelector('textarea');
textArea.addEventListener('keydown', e => {
if (e.key === 'Enter') {
window.alert('Sending data...');
e.preventDefault();
}
});
<textarea placeholder="Type and press enter"></textarea>
You can just put the submit code in a function, and call the function in both the cases:
function submitAction() {
fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputval.value+'&appid='+apik)
.then(res => res.json())
.then(data => {
const nameval = data['name']
const tempature = data['hourly']['pop']
city.innerHTML=`Weather of <span>${nameval}<span>`
temp.innerHTML = ` <span>${ tempature} </span>`
});
}
Then:
if (e.key === 'Enter') {
submitAction();
e.preventDefault();
}
And:
btn.addEventListener('click', () => submitAction());

You could use a HTML form and use the form submit event:
<form id="form">
<input type="text" placeholder="Enter any city..." id="cityinput" />
<button type="submit">Submit</button>
</form>
Inside the event listener you can then read the value from the input once the submit event is triggered. Alternatively you could go looking for the input value inside the event object.
var form = document.getElementById('form');
form.addEventListener('submit', function(event) {
const inputValue = document.querySelector('input').value;
event.preventDefault();
fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputValue+'&appid='+apik)
.then(res => res.json())
.then(data => {
var nameval = data['name']
var tempature = data['hourly']['pop']
city.innerHTML=`Weather of <span>${nameval}<span>`
temp.innerHTML = ` <span>${ tempature} </span>`
})
});

You need to create listener for keydown event and check if clicked key is enter:
const textarea = document.querySelector(".some-class");
textarea.addEventListener("keydown", function(e) {
if(e.key === "Enter") {
// your code
}
});
<textarea class="some-class"></textarea>

Related

performing a search on enter?

I have this form:
<form>
<label for="locationsearch">Location:</label>
<input type="search" id="locationsearch" name="locationsearch" />
</form>
I want to add an eventListener when I hit enter on the input(i.e. #locationsearch).
I tried doing this:
const locationSearch = document.getElementById("locationsearch");
locationSearch.addEventListener("search", () => {
console.log("search entered");
});
and this:
const locationSearch = document.getElementById("locationsearch");
locationSearch.onsubmit = function () {
console.log("search entered");
};
Both are not console-logging.
What is the correct/better way to perform this action?
The onsubmit event would happen on the form itself, not the input. So you could use an id on the form instead to target it directly.
const locationSearch = document.getElementById("locationsearch");
locationSearch.onsubmit = function () {
console.log("search entered");
};
<form id="locationsearch">
<label for="locationsearch">Location:</label>
<input type="search" name="locationsearch" />
</form>
You could handle it keydown event handler of input element. And check the key code if Enter key pressed.
const locationSearch = document.getElementById("locationsearch");
locationSearch.addEventListener("keydown", (e) => {
if (e.code === 'Enter') {
// Do Something ? Search
}
});
You can use keypress event for this.
const locationSearch = document.getElementById("locationsearch");
locationSearch.addEventListener("keypress", () => {
if (event.key === "Enter") {
event.preventDefault();
let inputVal = document.getElementById("locationsearch").value;
console.log("search entered "+inputVal);
document.getElementById("locationsearch").value = "";
}
});
<form>
<label for="locationsearch">Location:</label>
<input type="search" id="locationsearch" name="locationsearch" />
</form>

How to set default input for input keypress?

I have a webpage written in React (but it should not be strictly relevant to that question) that is composed by several inputs, let's call them Name, Surname and Code.
To work quickly, the insertion of the code is done with a Barcode Scanner that works as external keyboard. My idea is that if some field is focused, the keypress is inserted in the focused input but, in case no input is focused, I want to automatically focus and fill the Code input.
Is there a way to that it easily?
let inputName = document.querySelector('input[name="name"]');
let inputSurname = document.querySelector('input[name="surname"]');
let inputCode = document.querySelector('input[name="code"]');
let focusedInput = null;
[inputName, inputSurname, inputCode].forEach((input) => {
input.addEventListener('blur', () => {
focusedInput = null;
});
input.addEventListener('focus', () => {
focusedInput = input;
});
});
document.body.addEventListener('keypress', () => {
if (focusedInput == null) {
inputCode.focus();
}
});
<div>
<label>Name</label>
<input type="text" name="name" />
</div>
<div>
<label>Surname</label>
<input type="text" name="surname" />
</div>
<div>
<label>Code</label>
<input type="text" name="code" />
</div>
const surnameInput = document.getElementById('surname-input');
... (= do for all inputs)
let activeInput;
surnameInput.onFocus = () => { activeInput = surnameInput };
...
surnameInput.OnBlur = () => { activeInput = undefined };
...
document.addEventListener('keypress', (ev) => {
const input = activeInput ?? codeInput;
input.value += valueOftheKey;
}
You'd obviously have to evaluate if the key that was pressed has a value which you can add to the input, but I think this should give you an Idea of what to do. I haven't tried it out though, so it might not completely work.
Also: I'm not sure if it's the most efficient way, but it's an option.
EDIT: Answer by Kostas is better ;) except for the null...you should use undefined

Global array remains empty

I am trying to update my global array, but it remains null after I submit a text value(.name) through a submit button.
Please tell me how I can keep track of text values in my global array. Thank you.
var display_name = [];
document.addEventListener('DOMContentLoaded', () =>{
document.querySelector("#form1").onsubmit = () => {
let name = document.querySelector(".name").value;
display_name.push(name);
};
});
When the form is submitted, a new page is loaded. It loads the URL in the action property of the form. So, your variable goes away.
If you don't want that to happen, prevent the form from being submitted with preventDefault.
For example ...
const name_list = [];
window.addEventListener('DOMContentLoaded', (e) => {
const names = document.querySelector(`.names`);
const add_button = document.querySelector(`.names--add_button`);
names.addEventListener('submit', e => e.preventDefault());
add_button.addEventListener('click', (e) => {
const name = document.querySelector(`.names--name`);
const collected = document.querySelector(`.names--collected`);
name_list.push(name.value);
collected.innerHTML += `<li>${name.value}</li>`;
name.value = ``;
name.focus();
});
});
body { background: snow; }
<form class="names" action="#" method="post">
<label>Name: <input type="text" name="name" class="names--name"></label>
<button class="names--add_button">Add To List</button>
<div>Names Collected:</div>
<ul class="names--collected">
</ul>
</form>
I am see at the moment it's working perfect. but you want add value every time when you click the button. so just changed the type of your
<button type="submit"> to <button type="button">
because when you click on submit page automatically reload in html, an the 2nd thing you need to change your event from onsubmit to onclick and your button to it instead of your form.
var display_name = [];
document.addEventListener('DOMContentLoaded', () =>{
document.querySelector("#button1").onclick = () => {
let name = document.querySelector(".name").value;
display_name.push(name);
};
});

How to get value of input text field without knowing its id in Javascript

I have created a javascript script in which all clicks and action of a particular IP it tracked down when attached in a page. It all works fine except when the user searches something from an input field. I need to track that text which user has searched.
But I don't have any information regarding that input field i.e id or class also a page can have.
multiple input fields i.e A form for submission too.
I need to get that text when the enter key is pressed or any button(search) is pressed
In my case at present html page, I have below code.
<div class="navbar-form navbar-right">
<!-- Search Page -->
<div id="search-container" class="search-container" style="float: left;">
<div class="search-wrapper">
<div class="search-input-wrapper">
<input type="text" class="search-layouts-input" ng-model="searchQuery" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" placeholder="So, what are you looking for?" ng-keyup="$event.keyCode == 13 ? actionSearch() : null">
<button type="submit" class="s-layout-btn" ng-click="actionSearch();">
<svg id="Layer_1" width="20px" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="#222">
<defs>
<style>.cls-1{fill:none;stroke:#222;stroke-miterlimit:10;stroke-width:2px;}</style>
</svg>
</button>
</div>
</div>
</div>
<!-- Search Page -->
</div>
Is this the kind of thing that you're looking to implement? Of course most of it is pseudo code, but it's pretty straight-forward, just get all relevant inputs and buttons and whatnot, attach some event handler to them and update the application state.
I've included some basic functions that you may wish to fire in certain scenarios, such as onStateUpdate, there may be no need for this function, but it probably wouldn't hurt to keep it for the sake of simplcity.
I've used mostly ES6 oriented syntax because it allows you to achieve the same results with less code, I'm just that lazy.
The reason why I used a self invoked function just so there's no issues with variable names and nothing can be manipulated on the global scope, etc. If you'd like to read or know more about why self invoked functions can be pretty good, then I suggest you read sources such as this.
// Self invoked anonymous function.
(function() {
// The application state.
const state = {};
// Lazy way to use querySelectorAll
const $e = qs => document.querySelectorAll(qs);
// Make a copy of the state and make it global.
const getState = () => {
window.state = { ...state};
console.clear();
console.log(window.state);
};
// A function to run when the state updates.
const onStateUpdate = () => {
// Do some other stuff...
getState();
};
// Handle the key up event.
const inputHandler = (i, index) => i.onkeyup = () => {
i.id == null || i.id == '' ? i.setAttribute("id", index) : null;
const id = i.id;
state[id] = i.value;
onStateUpdate();
};
// Handle a button being clicked.
const clickHandler = btn => btn.onclick = onStateUpdate;
// Handle the enter key being pressed.
const enterHandler = e => e.keyCode == 13 ? onStateUpdate() : null;
// Assign all relevant events to the relevant functions.
const dispatchEvents = () => {
const inputs = $e("#search-container input[type=text]");
const buttons = $e("#search-container button");
inputs.forEach((i, index) => inputHandler(i, index));
buttons.forEach(b => clickHandler(b));
window.onkeypress = enterHandler;
};
// Fire the dispatch function.
dispatchEvents();
}());
<!-- this one does nothing as it's outside of the search-container element -->
<input type="text" id="testing" placeholder="I do nothing!" />
<div id="search-container">
<input type="text" id="test" />
<input type="text" id="demo" />
<input type="text" id="markup" />
<input type="text" />
<button>Search</button>
</div>
Older Syntax
// Self invoked anonymous function.
(function() {
// The application state.
var state = {};
// Lazy way to use querySelectorAll
var $e = function(qs) {
return document.querySelectorAll(qs);
};
// Make a copy of the state and make it global.
var getState = function() {
window.state = JSON.parse(JSON.stringify(state));
console.clear();
console.log(window.state);
};
// A function to run when the state updates.
var onStateUpdate = function() {
// Do some other stuff...
getState();
};
// Handle the key up event.
var inputHandler = function(i, index) {
i.onkeyup = function() {
if (i.id == null || i.id == '') {
i.setAttribute("id", index);
}
var id = i.id;
state[id] = i.value;
onStateUpdate();
};
};
// Handle a button being clicked.
var clickHandler = function(btn) {
btn.onclick = onStateUpdate;
};
// Handle the enter key being pressed.
var enterHandler = function(e) {
if (e.keyCode == 13) {
onStateUpdate();
};
};
// Assign all relevant events to the relevant functions.
var dispatchEvents = function() {
var inputs = $e("input[type=text]");
var buttons = $e("button");
inputs.forEach(function(i, index) {
inputHandler(i, index)
});
buttons.forEach(function(b) {
clickHandler(b)
});
window.onkeypress = enterHandler;
};
// Fire the dispatch function.
dispatchEvents();
}());
<input type="text" id="test" />
<input type="text" id="demo" />
<input type="text" id="markup" />
<input type="text" />
<button>Search</button>

Javascript push input into Array causes several arrays not one

This is a follow up to my question, seen here
I am trying to write that when a user enters in their name (string) into the field and hits enter, it pushes it into an array. It works, kinda. But I get an error when I try it one and then it produces multiple arrays when I try it another. I don't want to use jQuery.
Here is the HTML
<input type="text"
class="theplayer pre"
name="Player"
id="bind"
placeholder="Enter Names"
/>
<button type="button" id="thego" class="pre enterteam" value="click">Go</button>
Here is my js that works but it creates multiple arrays instead of pushing everything into one array (because the nextElementSibling is not called, I know this, see next block
let namesOfPlayers = [];
let currentValue = document.getElementById("bind").value;
let button = currentValue.nextElementSibling;
document.addEventListener('keypress', function (e) {
const key = e.which || e.keyCode;
if (key === 13) {
namesOfPlayers.push(currentValue);
console.log('namesOfPlayers', namesOfPlayers);
}
});
Here is my js that throws an error (I don't want to use jQuery)
I want that when a user hits enter or clicks the button that the string is submitted and added into the empty array. I can't for the life of me figure out how to make that work.
Thanks for your help!
You fetch the value of the input too soon. You should fetch it only when the button is clicked, not before.
Secondly, the button does not have a keypress event, nor a keyCode associated with it. You need to listen to the click event.
So do this:
let namesOfPlayers = [];
let input = document.getElementById("bind");
let button = input.nextElementSibling;
button.addEventListener('click', function (e) {
namesOfPlayers.push(input.value);
console.log('namesOfPlayers', namesOfPlayers);
});
<input type="text"
class="theplayer pre"
name="Player"
id="bind"
placeholder="Enter Names" />
<button type="button" id="thego" class="pre enterteam" value="click">Go</button>
Try this code, i added a click (for the button) and keypress (for the text input) events
so if you click enter when you focus on the text input the text in the input will be in the array.
and the same will happen if you click "Go" button
let namesOfPlayers = [];
let currentElement = document.getElementById("bind");
let button = currentElement.nextElementSibling;
let addPlayer = () => {
namesOfPlayers.push(currentElement.value);
console.log(namesOfPlayers); // Just for testing
}
currentElement.addEventListener('keypress', function (e) {
if (e.which === 13 || e.keyCode === 13) {
addPlayer();
}
});
button.addEventListener('click', addPlayer);
<input type="text"
class="theplayer pre"
name="Player"
id="bind"
placeholder="Enter Names"
/>
<button type="button" id="thego" class="pre enterteam" value="click">Go</button>
CurrentValue is defined outside of the event listener, so it only gets called once, on initialisation. That's why the push call only injects empty strings. Also, the button doesn't do anything because it doesn't have a listener.
Here's the updated code:
let namesOfPlayers = [];
// It's better to get the button by id instead of getting it by a previous child.
// This is because it might cause some unexpected behaviour if someone changed the HTML.
const button = document.getElementById("thego");
button.addEventListener('click', function (e) {
addItemToArray(namesOfPlayers);
});
document.addEventListener('keypress', function (e) {
const key = e.which || e.keyCode;
if (key === 13) {
addItemToArray(namesOfPlayers);
}
});
function addItemToArray(namesOfPlayers) {
const currentValue = document.getElementById("bind").value;
namesOfPlayers.push(currentValue);
console.log('namesOfPlayers', namesOfPlayers);
}
https://fiddle.jshell.net/4k4a9m6y/
But, you're better off with a form to improve performance.
let namesOfPlayers = [];
const form = document.getElementById("form");
form.addEventListener('submit', function (e) {
const currentValue = document.getElementById("bind").value;
namesOfPlayers.push(currentValue);
console.log('namesOfPlayers', namesOfPlayers);
});
<form id="form"
action="javascript:void(0);">
<input type="text"
class="theplayer pre"
name="Player"
id="bind"
placeholder="Enter Names"
/>
<button type="submit" id="thego" class="pre enterteam" value="click">Go</button>
</form>
https://fiddle.jshell.net/4k4a9m6y/2/

Categories