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);
};
});
Related
I've been trying to store an array from the the users input into localstorage and the output is not really encouraging as it gives inappropriate result:
<form action="index.php">
<input type="text" value=" " class="ex" >
<button id="ex">add item </button>
</form>
const items2 = document.querySelector('form');
items2.addEventListener('submit', function(ev) {
const items1 = document.getElementsByClassName('ex').value;
let items3;
if (localStorage.getItem('items3') === null) {
items3 = [];
} else {
items3 = JSON.parse(localStorage.getItem('items3'));
}
localStorage.setItem('items3', JSON.stringify(items3));
items3.push(items1);
alert('submit');
ev.preventDefault();
});
const items3 = JSON.parse(localStorage.getItem('items3'));
items3.forEach(function(items1) {
console.log(items1);
});
so, the problem I am facing exactly is that the alert always respond each time I click on the button which is but the localStorage file keeps giving the same value as an empty array [] regardless of any value I input into the text container. The forEach is also returning an error of
cannot read properties of an empty of null ('forEach')
The first time you run the script, nothing has been saved to local storage, so
const items3 = JSON.parse(localStorage.getItem('items3'));
will set items3 to null. That needs to have error checking to create a default value.
The submit listener needs to save to local storage after pushing the new item into the array.
There's no need to call localStorage.getItem() in the listener. You can just use the global items3 variable that's set when you read from local storage at the beginning.
const items2 = document.querySelector('form');
items2.addEventListener('submit', function(ev) {
const items1 = document.getElementsByClassName('ex').value;
items3.push(items1);
localStorage.setItem('items3', JSON.stringify(items3));
alert('submit');
ev.preventDefault();
});
const items3 = JSON.parse(localStorage.getItem('items3') || '[]');
items3.forEach(function(items1) {
console.log(items1);
});
<form action="index.php">
<input type="text" value=" " class="ex" >
<button id="ex">add item </button>
</form>
The reason you get null is because, document.getElementsByClassName('ex') returns a HTMLCollection. So, when you do document.getElementsByClassName('ex').value it doesn't contain a value but an object and then returns null; you'll need to iterate over it to retrieve values or specify an index, such as document.getElementsByClassName('ex')[0].value or better still, document.getElementById('ex').value
Here's a fix for you.
<form>
<input name="firstName" type="text" id="firstName" class="firstName" />
<button id="ex">add items</button>
</form>
const items2 = document.querySelector("form");
items2.addEventListener("submit", function (ev) {
ev.preventDefault();
let items1 = document.getElementById("firstName").value;
// or let items1 = document.getElementsByClassName("firstName")[0].value;
items3.push(items1);
localStorage.setItem("items3", JSON.stringify(items3));
document.getElementById("firstName").value = "";
alert("name added successfully")
});
const items3 = JSON.parse(localStorage.getItem("items3") || "[]");
items3.forEach(function (items1) {
console.log(items1);
});
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>
I want to append an li when the enter key is pressed using keydown. However, when I press the enter key the new li appears momentarily and then disappear.
How can I make it save the change or how can I fix the code?
var submitBtn = document.querySelector("input[type = 'submit'");
var enterTodo = document.querySelector("input[type = 'text']");
var todoList = document.querySelector("#todoList");
enterTodo.addEventListener('keydown', (event)=>{
if(event.which == 13){
var todo = enterTodo.value;
todoList.append("<li>" + todo + "</li>");
};
})
The reason why it was showing up and dissapearing almost immediately is because forms automatically refresh the page on submit. Which is why you have to use preventDefault in the onSubmit event.
I set up two working samples based on your code. In both, I went ahead and got your code to to append the proper li elements rather than the text `<li>${todo}</li>` to the todoList. I also made the enterTodo clear after being added to the list.
This uses the code about how you had it with the event listener on keydown, but it prevents the refresh.
var submitBtn = document.querySelector("input[type = 'submit'");
var enterTodo = document.querySelector("input[type = 'text']");
var todoList = document.querySelector("#todoList");
var form = document.querySelector("form");
form.onsubmit = (evt) => evt.preventDefault();
function addTodo() {
var todo = enterTodo.value;
var li = document.createElement('li');
li.textContent = todo;
todoList.appendChild(li);
enterTodo.value = "";
}
enterTodo.addEventListener('keydown', (event) => {
if (event.which == 13) {
addTodo();
};
})
<body>
<form>
<input type="text" onsubmit="" />
<input type="submit" />
<ul id="todoList"></ul>
</form>
</body>
This uses the from's onSubmit handler to perform the addition to the todoList instead of directly handling the enter key in the text input. This has the added benefit of also supporting the submit button click as well.
var submitBtn = document.querySelector("input[type = 'submit'");
var enterTodo = document.querySelector("input[type = 'text']");
var todoList = document.querySelector("#todoList");
var form = document.querySelector("form");
function addTodo() {
var todo = enterTodo.value;
var li = document.createElement('li');
li.textContent = todo;
todoList.appendChild(li);
enterTodo.value='';
}
form.onsubmit = (evt) => {evt.preventDefault();
addTodo();
}
<body>
<form>
<input type="text" onsubmit="" />
<input type="submit" />
<ul id="todoList"></ul>
</form>
</body>
I have a basic html form and when the user is successfully submitting the form I am displaying a pop-up. However, during that time two things occurs:
The popup is only displayed for 1-2 seconds
The page is reloaded and therefore going back to the top of the page
I would like to avoid those 2 events and apparently I have to use event.preventDefault() but I don't know where to use it
const messageSubmitContactForm = () => {
const form = document.getElementById("contact-form");
form.onsubmit = function(){
displayPopUpSent()
};
}
const displayPopUpSent = () => {
const popup = document.getElementById("popup-sent");
popup.style.display="block";
}
const app = () => {
messageSubmitContactForm();
}
app();
form
<form id="contact-form" method="post" action="" enctype="multipart/form-data"> content </form>
You should use it here
form.onsubmit = function(event){
event.preventDefault();
displayPopUpSent()
};
Update:
You need to add the action url too in your <form> element (currently it is an empty string)
I have created a simple snippet to illustrate a little bit, maybe this will clear it up for you.
const messageSubmitContactForm = () => {
const form = document.getElementById("contact-form");
form.onsubmit = function(event) {
event.preventDefault();
displayPopUpSent()
};
}
const displayPopUpSent = () => {
const popup = document.getElementById("popup-sent");
popup.style.display = "block";
}
const app = () => {
messageSubmitContactForm();
}
app();
<html>
<body>
<form id="contact-form" method="post" action="" enctype="multipart/form-data">
<input type="text" name="message" />
<button type="submit">Submit</button>
</form>
<div id="popup-sent" style="display: none">Data is sent</div>
</body>
</html>
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/