The changes occurs briefly using keydown and then disappear - javascript

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>

Related

Javascript | Pressing the enter button on the keyboard, the HTML button should be pressed

Pressing the enter button on the keyboard, the HTML button (id="botonCorregir") should be pressed automatically, but does nothing.
HTML:
<form id="theFormID" class="text-center">
<input autofocus id="respuestaUsuario" type="text">
<button id="botonCorregir" onclick="corregir()">Responder</button>
</form>
JAVASCRIPT:
<script>
//This should push the html button
var input = document.getElementById("respuestaUsuario");
input.addEventListener("keyup", function(event) {
if (event.keyCode == 13) {
event.preventDefault();
document.getElementById("botonCorregir").click();
}
});
</script>
<script>
//This corrects the user answer
function corregir(){
var respUs = document.getElementById('respuestaUsuario').value;
var respUs=respUs.toLowerCase();
var respuestasDj = document.getElementsByClassName("idRespuesta");
var cantidad = respuestasDj.length;
var resultado = "incorrecto";
for(i = 0; i < cantidad; i++){
var respPosible = document.getElementsByClassName("idRespuesta")[i].getAttribute('value');
if(respUs == respPosible){
var resultado = "correcto";
}
}
}
</script>
For example if y try that, and push enter, doesn´t show alert "hello!". Why?
<script>
if (event.keyCode == 13) {
alert("hello!");
}
</script>
The usual way to do it in html/js is this one:
HTML
<form id="my-form">
<!-- creating a form, we use the on-submit event -->
<input type="text" autofocus id="respuestaUsuario" />
<button type="submit">Responder</button>
</form>
JS
// submit event runs when the user click the submit button or press enter on the input-text
document.getElementById('my-form').addEventListner('submit', evt => {
evt.preventDefault();
corregir();
});
Let me know if it's not clear enough and I'll try to explain it better.
the keyup event listener is for when you release the enter key
plus you can call the corregir function directly instead of triggering a click on the button
try :
<script>
//This should push the html button
var input = document.getElementById("respuestaUsuario");
input.addEventListener("keyup", function(event) {
if (event.keyCode == 13) {
event.preventDefault();
corregir();
}
});
//This corrects the user answer
function corregir(){
var respUs = document.getElementById('respuestaUsuario').value;
var respUs=respUs.toLowerCase();
var respuestasDj = document.getElementsByClassName("idRespuesta");
var cantidad = respuestasDj.length;
var resultado = "incorrecto";
for(i = 0; i < cantidad; i++){
var respPosible = document.getElementsByClassName("idRespuesta")[i].getAttribute('value');
if(respUs == respPosible){
var resultado = "correcto";
}
}
}
</script>
also, a submit would be more addapted to this situation since the submit triggers itself on enter if an element of it's form is selected
Try to call the function direktly without clicking the button.
if (event.keyCode == 13) {
event.preventDefault();
corregir();
}

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);
};
});

Search by pressing the enter key on keyboard

Trying to also search by pressing enter key. Works with the button but for some reason the code i have for the key press is not working.
Javascript:
function displayMatches() {
const searchText = document.querySelector('.search').value;
const matchArray = findMatches(searchText, name);
const html = matchArray.map(place => {
const regex = new RegExp(searchText);
const nameName = place.name.replace(regex, `<span class="hl">${searchText}</span>`);
return `
<a href="${place.url}" target="_blank">
<li>
<span class="name">${nameName} <br> ${(place.price)}</span>
<img src="${place.imgurl}" alt="Drink Image" height="87.5" width="100">
</li>
</a>
`;
}).join('');
suggestions.innerHTML = html;
}
const suggestions = document.querySelector('.suggestions');
const searchBtn = document.querySelector('.btn-search');
searchBtn.addEventListener('click', displayMatches);
var input = document.getElementById('.search');
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById('.btn-search').click();
}
});
In:
document.getElementById('.btn-search').click();
Are you sure .btn-search is a id property? Seems like a class property. You cannot get the element with getElementById if the "btn-search" isn't the id of the element.
And you don't need to set "." (class) or "#" (id) on the getElementById (getElementById it's only to get elements by id, so you don't need to tell the script the property type you searching).
As the user William Carneiro stated, the issue is the . character.
The function getElementById just receive the id, not a selector. Check documentation
Change this line:
var input = document.getElementById('.search');
With something like this:
var input = document.getElementById('search');
... or this:
var input = document.querySelector('#search');
Also, make sure that your element has id="search", it seems that probably you want to find an element with the class search instead.
var input = document.querySelector('.search');
I found this and I think it can helped you
JavaScript:
function myFunction(event) {
var x = event.keyCode;
if (x == 27) {
// 27 is the ESC key
alert ("You pressed the Escape key!");
}
}
Ok most of your code was working
A few things to note
When using query selector and calling a class use the class name with the dot'.search-btn'
When using getElementById remember there is no Dot 'search-btn'
Also I think I added an id in few places make sure your html tags have Id attributes to them before using getElementById i.e class='search-btn' id='search-btn' ...>
Other than that your code works
function displayMatches() {
const searchText = document.querySelector('.search').value;
// the rest of your code here
console.log("enter Worked Searching" );
}
const suggestions = document.querySelector('.suggestions');
const searchBtn = document.querySelector('.btn-search');
searchBtn.addEventListener('click', displayMatches);
var input = document.getElementById('search');
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById('btn-search').click();
}
});
<input class="search" id = 'search'type="text" placeholder="Search Deals">
<input type='button' class='btn-search' value='search' id ='btn-search'>

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/

Onblur event fires before new dynamic input is created using JavaScript

I'm dynamically adding text inputs to a form. The new input also receives focus. On adding an onblur event however the onblur event seems to be firing as soon as the input is added. To test this I added an alert for the onblur event. The alert appears, and only after clicking OK is the new input created. This happens in IE, Firefox and Opera.
The following is the code I am using. I have removed all other code to for ease of reading.
<head><title>""</title>
<script type="text/javascript">
var count = 1;
function addinput () {
var inpmaster = document.getElementById("inpMaster");
var myinput = document.createElement("input");
myinput.id = "myfield"+count;
myinput.name = "myfield"+count;
myinput.type = "text";
myinput.onblur = alert("woot");
inpmaster.parentNode.insertBefore(myinput,inpmaster);
inpmaster.disabled="disabled";
myinput.focus();
count++;
};
</script>
</head>
<body>
<form action="" method="post" id="admin">
<input id="inpMaster" type="text" name="prodDesccc" onfocus="addinput();" />
</form>
</body>
It is because you are using alert("woot") to assign to onblur event instead of function(){ alert("woot") ;}.
Change your code to:
function addinput () {
var inpmaster = document.getElementById("inpMaster");
var myinput = document.createElement("input");
myinput.id = "myfield"+count;
myinput.name = "myfield"+count;
myinput.type = "text";
myinput.onblur = function(){alert("woot");};
inpmaster.parentNode.insertBefore(myinput,inpmaster);
inpmaster.disabled="disabled";
myinput.focus();
count++;
};

Categories