I have a input where a user can input text and when the user presses enter on their keyboard, it will click the button 'Go!' which should then make the 'Create Div' button appear. And a div is created with the user's inputted text, when they click the 'Create Div' button. But I want this button to be clicked also when the user presses enter. Thus when the user presses 'Enter' the first time, it will click the 'Go!' button which will make the 'Create Div' button appear and then when the user presses 'Enter' the second time ( or preferably when the 'Create Div' button is shown on the screen) then the actual div will be created with the user's inputted text.
I tried doing this in Javascript, by using an IF statement but right now when I press 'Enter' the first time to trigger the 'Go!' button, it automatically triggers the 'Create Div' button and the div appears right after the first 'Enter' is pressed (uncomment the last bit of my JS code to see what I mean) What should I change to get my desired result?
var button = document.getElementById("button");
var createbutton = document.createElement("button");
var creatediv = document.createElement("div");
button.addEventListener('click', function(){
createbutton.innerHTML = "Create Div";
createbutton.style.display = 'inline-block';
document.getElementById("body").appendChild(createbutton);
});
createbutton.addEventListener('click', function(){
createbutton.style.display = 'none';
var input = document.getElementById("input").value;
creatediv.innerHTML = input;
document.getElementById("body").appendChild(creatediv);
});
document.onkeydown = function(event){
if(event.keyCode == 13){
button.click();
}
}
/*if(createbutton.style.display = 'inline-block'){
document.onkeydown = function(event){
if(event.keyCode == 13){
createbutton.click();
}
}
}*/
<body id="body">
<input type="text" id="input" placeholder="Text goes here">
<button id="button">Go!</button>
</body>
You can give your createbuttonand ID and check if the element is inside the DOM
when enter is pressed:
var button = document.getElementById("button");
var createbutton = document.createElement("button");
var creatediv = document.createElement("div");
button.addEventListener('click', function(){
createbutton.innerHTML = "Create Div";
createbutton.style.display = 'inline-block';
createbutton.id = 'createButton';
document.getElementById("body").appendChild(createbutton);
});
createbutton.addEventListener('click', function(){
createbutton.style.display = 'none';
var input = document.getElementById("input").value;
creatediv.innerHTML = input;
document.getElementById("body").appendChild(creatediv);
});
document.onkeydown = function(event){
if(event.keyCode === 13) {
if(document.getElementById('createButton')) {
createbutton.click();
} else {
button.click();
}
}
}
<body id="body">
<input type="text" id="input" placeholder="Text goes here">
<button id="button">Go!</button>
</body>
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’m new to Js.. and I’m trying to change the inner Text of a button to toggle on click between On and Off using addEventListener method.
const btn = document.getElementsByClassName("btn")[0];
const btn2 = document.createTextNode("Off");
btn.addEventListener.toggle("click", modifiedText() {
// enter code here
});
ModifiedText() {
// enter code here
}
<button class=“btn”>On</button>
Just addEventListener on button and get or set the text inside button using textContent property.
const button = document.querySelector(".btn");
button.addEventListener("click", function clickHandler( e ) {
const btnText = e.target.textContent;
if( btnText.toLowerCase() === "on") e.target.textContent = "Off";
else e.target.textContent = "On"
})
<button class="btn">On</button>
I expect the behavior of the program listed below to be like this:
I click on the input.
I press enter.
The line "Press Enter once again" appears.
I go out of input by clicking somewhere on the page.
I press Enter.
Then the line "You have pressed Enter 2 times" appears.
The real behavior of this program:
I click on the input.
I press enter.
The lines "Press Enter once again" and "You have pressed Enter 2 times" appear.
I have 2 questions:
1) What is the reason for that? I have pressed Enter only once.
2) How to make this program behave the way I expect it to behave?
let input = document.createElement("input");
input.value = "Click on this field and press Enter";
input.addEventListener("keydown", function(){
if(event.keyCode === 13){
let div2 = document.createElement("div");
div2.innerHTML = "Press Enter once again";
document.addEventListener("keydown", function(){
if(event.keyCode === 13){
let div3 = document.createElement("div");
div3.innerHTML = "You have pressed Enter 2 times";
document.body.appendChild(div3);
}
});
document.body.appendChild(div2);
}
});
document.body.appendChild(input);
Let's break this down. What is happening is that your if condition is immediately checking if the key was pressed, and it has been so e.keyCode is always 13.
The easiest method to solve this is with the following bit of code:
let input = document.createElement("input");
let isPressed = false;
input.value = "Click on this field and press Enter";
document.addEventListener("keydown", function(e) {
if (event.keyCode === 13 && isPressed) {
let div3 = document.createElement("div");
div3.innerHTML = "You have pressed Enter 2 times";
document.body.appendChild(div3);
}
});
input.addEventListener("keydown", function(e){
event.stopPropagation()
if(event.keyCode === 13){
if ( isPressed ) {
return;
} else {
let div2 = document.createElement("div");
div2.innerHTML = "Press Enter once again";
isPressed = true;
document.body.appendChild(div2);
}
}
});
document.body.appendChild(input);
You can try that out here. You can refractor this to your liking. :)
Keeping your original code in mind, here is the updated version.
To understand how this bit works, it's simple: when there is an event in element a and the wrapper for that element is b, the event travels up through a process known as event bubbling (because bubbles rise up).
Due to that, the second event listener, on the document, gets executed.
To stop that from happening, you can use .stopPropagation() on the event object.
There were a couple of things going on here. You were attaching the listener twice, the second time on the whole document, this event then got triggered instantly when the event bubbled. You didn't need to use two different elements for the message either, if you keep track of if enter was pressed. You should also use textContent over innerHTML for security reasons :)
Here is the code rewritten
let enterHasBeenPressed = false;
let input = document.createElement("input");
input.value = "Click on this field and press Enter";
input.addEventListener("keydown", function(){
if(event.keyCode === 13){
onEnterPressed();
}
});
document.body.appendChild(input);
let text = document.createElement("div");
document.body.appendChild(text);
function onEnterPressed() {
if (!enterHasBeenPressed) {
text.textContent = "Press Enter once again";
enterHasBeenPressed = true;
return;
}
text.textContent = "You have pressed Enter 2 times";
}
https://codepen.io/anon/pen/wbjojR
I'm trying to set up a input box using a div, but I'm having some difficulty finding how to clear the text box upon pressing enter.
I've searched for a solution and have found this code that uses an eventListener and a function.
var messageinputbox = document.createElement("input");
messageinputbox.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById('chatbox').value = "";
}
});
document.getElementById("messageinput").appendChild(messageinputbox);
The fuction does not work, even though I do not see any syntax errors in it, and my javascript file doesn't give me any errors.
You never gave the new input box the ID chatbox. You need
messageinputbox.id = "chatbox";
But there's no need for the ID, since the messageinputbox variable holds a reference to the input box. Just use that variable in the function.
var messageinputbox = document.createElement("input");
messageinputbox.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
messageinputbox.value = "";
}
});
document.getElementById("messageinput").appendChild(messageinputbox);
<div id="messageinput"></div>
Try this sample code:
<html>
<head>
<title>Javascript key press demo</title>
<script type='text/javascript'>
function clearTextonEnterKeyPress(e){
if(e.keyCode == 13){
alert("You Have Pressed Enter Key.");
document.getElementById('test').value = "";
alert('Text Cleared');
}
}
</script>
</head>
<body>
Press Enter Button in text box
<input type='text' onkeypress='clearTextonEnterKeyPress(event)' id='test'>
</body>
</html>
I knew how to fix this but right now I just don't remember. What I am doing is dynamically create two input elements: a text-box and a button. When I press on the button I want an alert with the text-box's value
var Form = {
Create: function() {
var Input = document.createElement('input');
Input.type = 'text';
document.body.appendChild(Input);
var Button = document.createElement('input');
Button.type = 'button';
Button.value = 'Show Value';
document.body.appendChild(Button);
Button.onclick = function() {
alert(Input.value);
}
}
}
window.onload = function() { Form.Create(); }
When I click on the button I get an empty message, even if the text-box contains text. So, I want the function to get the content of the text-box in real-time but I just don't know how this was done.
it seems that you are appending an other button
change this line :
document.body.appendChild(LoginButton);
by this:
document.body.appendChild(Button);