I am using addEventListener to bind an event to a node. The addEventListener adds addItem function to node. But when I press enter the function is not running.
Here is the JavaScript:
document.getElementById('add-item').addEventListener('keypress', function (e) {
if (e.keyCode == 13) {
addItem();
}
}, false);
function addItem() {
var list = document.querySelector('ul.todo-list');
var newItem = document.getElementById('new-item-text').value;
var newListItem = document.createElement('li');
newListItem.className = 'todo-item';
newListItem.innerHTML = newItem + '<span class="remove"></span>';
list.insertBefore(newListItem, document.querySelector('.todo-new'));
//1. Empty the Input field once the item
document.getElementsByTagName('input')[0].value = '';
}
Here is the HTML:
<li class='todo-new'>
<input id='new-item-text' type='text'/>
<a id='add-item' href='#'>+</a>
</li>
On other hand the function runs with click
document.getElementById('add-item').addEventListener('click', addItem, false);
I want to do this with JavaScript only not using jQuery library.
Edited:
I want to attach the event to input field.
I'm willing to place a bet that the add-item element isn't in focus when you press enter. Instead, try changing the trigger to be the input field.
document.getElementById('new-item-text').addEventListener('keypress', function (e) {
if (e.keyCode == 13) {
addItem();
}
}, false);
Related
I'm trying to make a grocery list app that functions as a to-do list. I've got most of the basics down for it so far. I've got a button that takes the input field value, adds it to an array, and displays it to the page. However, I would also like for this to trigger by pressing the enter key. I've given it a shot and so far I've had no luck. I'm not sure why, but instead of just triggering from the enter key, it is creating a new item on the page with every keypress. I would also like to know how to make it so that if the input field is empty, then nothing happens upon click or enter keypress.
let addButton = document.getElementById('add-button');
addButton.addEventListener('click', add);
let addInput = document.getElementById('add-input');
addInput.addEventListener('keydown', add);
//let removeButton = document.getElementById('remove-button');
//removeButton.addEventListener('click', remove);
let groceryList = []
function add() {
groceryInput = addInput.value;
groceryList.push(groceryInput);
addInput.value = '';
displayGroceries();
}
function remove(event) {
let position = event.currentTarget.id;
groceryList.splice(position, 1);
displayGroceries();
}
function displayGroceries() {
let groceryUl = document.getElementById('grocery-ul');
groceryUl.innerHTML = '';
for (var i = 0; i < groceryList.length; i++) {
let groceryLi = document.createElement('li');
groceryLi.innerHTML = groceryList[i];
groceryUl.appendChild(groceryLi);
let removeButton = document.createElement('button');
removeButton.innerText = "Remove";
removeButton.addEventListener('click', remove);
removeButton.id = i;
groceryLi.appendChild(removeButton);
if (add.keyCode === 13) {
add();
}
}
}
<div class="container">
<h1>Grocery List</h1>
<input id="add-input" placeholder="Add Groceries" autocomplete="off">
<button id="add-button">Add</button>
<!--<button id="remove-button">Remove</button>-->
<div>
<ul id="grocery-ul">
</ul>
</div>
You use 'keydown' event which fire when any key is pressed not only enter key. To call add function only for enter press you must customize it. Like -
if(key.which == 13) {
add();
}
And to prevent post empty input value you must check it.
if(groceryInput) {
groceryList.push(groceryInput);
addInput.value = '';
displayGroceries();
}
working Fiddle - https://jsfiddle.net/0xtzb5mg/1/
'keydown' is an event which will work if any key is pressed. You have to specify the keyCode of the key if you need an action to be taken when a particular key is pressed.
In your requirement, the enter key is used and the keyCode for enter key is 13.
document.addEventListener("keydown", function(event) {
if(event.keyCode === 13){
add();
}
});
You can check the keycode for all the keys in this link http://gcctech.org/csc/javascript/javascript_keycodes.htm
I would like my function to execute while pressing the submit button (that already exists) or on pressing the enter key in either of any of the 3 inputs (Id's: taskInfo, dueDate, dueTime).
I've tried separating the function and doing it that way but it did not work at all..
function init() {
window.notes = getLocalStorage('notes') || [];
setNotesUi();
// make note with form inputs by using button +reset notes+ set localStorage
var submitElement = document.getElementById('submit');
submitElement.addEventListener('click', function ()
Gonna need the following function to execute while pressing enter either anywhere or while specifically on 3 inputs called (taskInfo, dueDate, dueTime)
just like here it works with a mouse click only on the submit button
{
var taskInfoElement = document.getElementById('taskInfo');
var dueDateElement = document.getElementById('dueDate');
var dueTimeElement = document.getElementById('dueTime');
var note = {
taskInfo: taskInfoElement.value,
dueDate: dueDateElement.value,
dueTime: dueTimeElement.value
};
notes.push(note);
setNotesUi();
setLocalStorage('notes', notes);
});
}
Gonna need the following function to execute while pressing enter either anywhere or while specifically on 3 inputs called (taskInfo, dueDate, dueTime)
just like here it works with a mouse click only on the submit button
Forms already handle this. Just add a submit handler. Enter on any of the textboxes will trigger it. No extra JavaScript is needed.
document.querySelector("#myForm").addEventListener("submit", evt => {
console.log("Submit called");
evt.preventDefault();
});
<form id="myForm">
<label for="a">A</label><input id="a"/>
<label for="b">B</label><input id="b"/>
<label for="c">C</label><input id="c"/>
<button>d</button>
</form>
Define your function
function submitForm ()
{
var taskInfoElement = document.getElementById('taskInfo');
var dueDateElement = document.getElementById('dueDate');
var dueTimeElement = document.getElementById('dueTime');
var note = {
taskInfo: taskInfoElement.value,
dueDate: dueDateElement.value,
dueTime: dueTimeElement.value
};
notes.push(note);
setNotesUi();
setLocalStorage('notes', notes);
}
Define a function that will be called on textbox keydown event, which will track if the enter key is pressed on the textboxes.
function keyPressed(e){
if (!e) { var e = window.event; }
e.preventDefault(); // sometimes useful
// Enter is pressed
if (e.keyCode == 13) { submitForm(); }
}
Finally, your init function to initialize everything and bind these functions appropriately.
function init() {
window.notes = getLocalStorage('notes') || [];
setNotesUi();
document.getElementById('submit').addEventListener('click',submitForm);
document.getElementById('taskInfo').addEventListener("keydown",keyPressed);
document.getElementById('dueDate').addEventListener("keydown",keyPressed);
document.getElementById('dueTime').addEventListener("keydown",keyPressed);
}
I am a total beginner and am learning front-end using a "just do it" and project-focus route.
My web app will essentially work similar to that of a to-do list.
I assume it is because I have "getElementById" twice for the same element.
This works initially:
// add idea to list button
document.getElementById('btnSubmit').addEventListener("submitIdea", submitIdea);
function submitIdea() {
var ul = document.getElementsByClassName('anIdea')[0];
var enterIdea = document.getElementById('enterIdea');
var li = document.createElement('li');
li.setAttribute('class', enterIdea.value);
li.appendChild(document.createTextNode(enterIdea.value));
ul.prepend(li);
li.contentEditable = 'true';
};
But then, when I add this code, I am unable to write anything at all in my input box:
// use enter key to submit new li item
document.getElementById("enterIdea").addEventListener('keypress', function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById('btnSubmit').click();
}
});
These are the resources I used:
https://memorynotfound.com/dynamically-addremove-items-list-javascript/
Trigger a button click with JavaScript on the Enter key in a text box
your code is ok in general
document.getElementById('btnSubmit').addEventListener("click", function() {
var ul = document.getElementsByClassName("anIdea")[0];
var enterIdea = document.getElementById("enterIdea");
var li = document.createElement("li");
li.setAttribute('class', enterIdea.value);
li.contentEditable = "true";
li.appendChild(document.createTextNode(enterIdea.value));
ul.prepend(li);
});
document.getElementById("enterIdea").addEventListener("keypress", function(event) {
if (event.keyCode === 13) {
document.getElementById("btnSubmit").click();
}
});
Instead of trying to "click" the button with javascript, simply call the desired function on the enter key press.
document.addEventListener("keypress", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById('btnSubmit').click();
}
});
I have a textbox which needs to be filled with website URL. So when user places the cursor in the textbox then the textbox should prefill with "http://" (Not a placeholder).
If the user does not enter anything and moves to the next textbox then the textbox have empty value
If the user fills the textbox then the value is unchanged
I tried below Javascript code but did not work:
if (document.activeElement.id == 'input-textbox-id' && !document.activeElement.value) {
document.querySelector("#input-textbox-id").value="http://";
} else if (document.activeElement.id != 'input-textbox-id' && (!document.activeElement.value || document.activeElement.value == 'http://')) {
document.querySelector("#input-textbox-id").value="";
}
You can use the focus and blur events for this.
Assuming that the variable textBox contains the reference to your textBox element, you can use the following code:
let textBox = document.getElementById("a");
textBox.addEventListener("focus", function() {
if (!this.value) {
this.value += "http://";
}
});
textBox.addEventListener("blur", function() {
if (this.value == "http://") {
this.value = "";
}
});
<input type="text" id="a">
You will need to attach event listener by using addEventListener. Events you need: focus and focusout.
We add .http-prefill class for all inputs. We iterate over inputs array and attach event.
Please do not forget to remove eventListener when you are done eg. you unload the form.
To do so, just copy the code for adding listeners and replace addEventListener with removeEventListener.
inputs.forEach(function(input) {
input.removeEventListener('focus', onFocus);
input.removeEventListener('focusout', onFocusOut);
});
Example code:
var fillValue = 'http://';
var onFocus = function() {
this.value = fillValue;
}
var onFocusOut = function() {
if (this.value === fillValue) {
this.value = '';
}
}
var inputs = document.querySelectorAll('.http-prefill');
inputs.forEach(function(input) {
input.addEventListener('focus', onFocus);
input.addEventListener('focusout', onFocusOut);
});
.http-prefill {
width: 100%;
margin-bottom: 5px;
}
<input class="http-prefill" name="input-0" />
<input class="http-prefill" name="input-1" />
<input class="http-prefill" name="input-2" />
<input class="http-prefill" name="input-3" />
you can use some key events like onKeyDown and when keydown you can get hold of old value and append it with new value.
let keyPressed = true
function onKeyDown(event) {
if(keyPressed && event.keyCode !== 8)
{
keyPressed = false;
let oldvalue = document.getElementById('input-textbox-id').value;
document.getElementById('input-textbox-id').value = "http://"+oldvalue
}
if(!document.getElementById('input-textbox-id').value)
{
keyPressed = true;
}
}
here is working code. http://jsbin.com/zoxiwokepi/edit?html,output
I made simple web chat, bubles ( messages) above one text field (input message) and send button. How to make that input text field holds focus and not to lose when I click on something else (to focus always be on input with id="input_message") ?
var el = document.getElementById('input_message');
el.focus();
el.onblur = function () {
setTimeout(function () {
el.focus();
});
};
Here's the fiddle: http://jsfiddle.net/MwaNM/
Here's a dirty hack.
<input type="text" id="input_message" />
<script type="text/javascript">
with (document.getElementById('input_message')) {
onblur = function(e) {
var elm = e.target;
setTimeout(function(){elm.focus()});
}
onkeydown = function(e) {
var key = e.which || e.keyCode;
if (key == 9) e.preventDefault();
// code for tab is 9
}
}
</script>
var inputElement = document.getElementById("input_message");
inputElement.focus();
inputElement.addEventListener("blur", function(event){
inputElement.focus();
});
http://jsfiddle.net/653w1mpv/