I currently use the following code to save input after browser refresh.
<style>textarea, input {
width:100%;
height:50px
}
</style>
<textarea class='' id='thetext' onkeyup='saveValue(this)'/><br/><br/>
<button id='' onclick='shift()'>Shift</button><br/><br/>
<script>
var input = document.getElementById("thetext");
function shift() { input.value = input.value.toUpperCase()}
</script>
<script>document.getElementById("thetext").value = getSavedValue("thetext");
function saveValue(e){
var id = e.id;
var val = e.value;
localStorage.setItem(id, val);
}
function getSavedValue (v){
if (!localStorage.getItem(v)) {
return "";
}
return localStorage.getItem(v);
}</script>
When a user enters something in the textarea, and leaves the window, the textarea gets stored in local storage, thanks to the onkeyup event listener.
However, if the user presses the shift button and leaves the browser, the uppercase text value doesn't get stored in textarea because there's no onkeyup action after button press.
I tried various event listeners instead of onkeyup, like onblur, onunload but none of them are working. Is there any event listener which can record the actions then and there? Or any way else?
PS - This code isn't working on Stackoverflow, don't know why, however it's working on my webpage. So, Please ignore this issue.
You can just call the saveValue() method after you´ve done all your stuff you need with the input.
just update the saved value by calling the savevalue() method you defined like this input.value = input.value.replace(); input.saveValue()
Run this in your own environment.
<form>
<input name="first" placeholder="first" />
<input name="last" placeholder="last" />
</form>
<script>
const form = document.querySelector('form');
const FORM_DATA = 'FORM-DATA';
window.addEventListener('DOMContentLoaded', () => {
const fromStorage = localStorage.getItem(FORM_DATA);
if (!fromStorage) return;
const json = JSON.parse(fromStorage);
for (const input of form.querySelectorAll('input')) {
input.value = json[input.name];
}
});
form.addEventListener('keyup', () => {
const formData = Object.fromEntries([...new FormData(form)]);
localStorage.setItem(FORM_DATA, JSON.stringify(formData));
});
</script>
Here is an example that works :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Save input after refreshing</title>
</head>
<body>
<input id="myInput" type="text" />
<script>
function saveValue(inputElement) {
if (!inputElement) throw new Error('inputElement param is required');
const { id, value } = inputElement;
if (!id) throw new Error('inputElemend should have an id attribute');
localStorage.setItem(id, value);
}
function getSavedValue(inputElement) {
if (!inputElement) throw new Error('inputElement param is required');
const { id } = inputElement;
if (!id) throw new Error('inputElemend should have an id attribute');
const value = localStorage.getItem(id);
return value;
}
const input = document.querySelector('#myInput');
input.addEventListener("keyup", function(event) {
saveValue(event.target)
});
window.addEventListener('load', function() {
const value = getSavedValue(input);
input.value = value;
})
</script>
</body>
</html>
Related
I have an idea to create multiple inputs from single input and get their all values. But I can only get the first input value but not the rest. Can someone tell me how to do it?
const singleInput = document.getElementById('singleInput')
const demo = document.getElementById('demo')
const demo2 = document.getElementById('demo2')
const multipleInputValue = []
singleInput.addEventListener('keyup', function (event) {
if (event.key == 'Enter') {
demo2.innerHTML += singleInput.value + '<input
type="number"
class="multipleInput" onkeyup="getValue(event)">' +
'<br>'
multipleInput =
document.getElementsByClassName('multipleInput')
}
})
function getValue(event) {
if (event.key == 'Enter') {
multipleInputValue.push(multipleInput[0].value)
}
}
And here's the HTML Code for this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Coding</title>
</head>
<body>
<input type="text" id="singleInput">
<div id="demo">
<p id="demo2"></p>
</div>
<script src="script.js"></script>
</body>
</html>
Your getValue function (bound to onkeyup event of the input appended at runtime) was trying to get the value of the input with multipleInput[0].value but no piece of code was pushing values to that array.
A better approach was to just using event.target to retrieve the object firing the event from the event handler itself.
I showed here a simplified demo of your code showing that concept.
When you press enter on the first input, the second one will appear.. after then if you press keys inside that new input, a console.log will show the activity, including when you'll press enter (and the value will be pushed to the array).
But the overall logic wasn't pretty clear so I couldn't go any further
const multipleInput = [];
const singleInput = document.getElementById('singleInput');
singleInput.addEventListener('keyup', function (event) {
if (event.key == 'Enter') {
console.log('singleInput: pressed ENTER');
const inputElement = event.target;
const target = document.getElementById('target');
target.innerHTML +=
inputElement.value +
'<input type="number" class="multipleInput" onkeyup="getValue(event)"><br>';
}
});
function getValue(event) {
console.log(`Key was pressed for the new created input: ${event.key}`);
if (event.key == 'Enter') {
console.log(`The value pushed to the array is: ${event.target.value}`);
multipleInput.push(event.target.value)
}
}
.multipleInput{
margin-bottom: 1rem;
margin-left: 1rem;
}
#singleInput{
margin-bottom: 2rem;
}
<input type="text" id="singleInput">
<div id="target">
</div>
I followed a tutorial on Youtube about localStorage and everything went fine. After that I tried to mess around with the concepts and wanted to add a button to remove the localStorage (id ="btnClear").
Now I've tried everything but it doesnt let me remove the storage. I think its because I declared the constants inside the function and I might have to store them somewhere outside and stringify the input. But can I clear the localStorage somehow even in this scenario?
<body>
<content>
<fieldset>
<legend>Insert Data</legend>
<input type="text" id="inpKey" placeholder="Insert Key.." />
<input type="text" id="inpValue" placeholder="Insert Value.." />
<button type="button" id="btnInsert">Insert</button>
</fieldset>
<fieldset>
<legend>Local Storage</legend>
<div id="lsOutput"></div>
<br />
<button type="button" id="btnClear">Clear</button>
</fieldset>
</content>
</body>
<script type="text/javascript">
const inpKey = document.getElementById("inpKey");
const inpValue = document.getElementById("inpValue");
const btnInsert = document.getElementById("btnInsert");
const lsOutput = document.getElementById("lsOutput");
const btnClear = document.getElementById("btnClear");
btnInsert.onclick = function () {
const key = inpKey.value;
const value = inpValue.value;
if (key && value) {
localStorage.setItem(key, value);
location.reload();
}
};
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
lsOutput.innerHTML += `${key}: ${value}`;
}
//BUTTON CLEAR
btnClear.onclick = function () {
localStorage.clear();
};
</script>
Check your local storage in the browser. Your code actually does clear the localStorage. What you are missing is to update your UI. Replace your Button clear code with that:
btnClear.onclick = function () {
localStorage.clear();
if(localStorage.length === 0)
lsOutput.innerHTML = "";
};
Here is a tutorial how you check your local storage in chrome for example: How to view or edit localStorage
Have a look here, I have update all you code from HTML to JS.
You can test it on jsfiddle as stackoverflow will throw this error:
{
"message": "Uncaught SecurityError: Failed to read the 'localStorage' property from 'Window': The document is sandboxed and lacks the 'allow-same-origin' flag.",
"filename": "https://stacksnippets.net/js",
"lineno": 37,
"colno": 33
}
Also, It is better to use document.addEventListener with most of your events (as they provide you with reacher experience)
See more on events here
A quote from this URL:
The significant drawback with inline events is that unlike event
listeners described above, you may only have one inline event
assigned. Inline events are stored as an attribute/property of the
element[doc],
meaning that it can be overwritten.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>How to clear localStorage on button click</title>
</head>
<body>
<content>
<fieldset>
<legend>Insert Data</legend>
<input type="text" id="inpKey" placeholder="Insert Key.." />
<input type="text" id="inpValue" placeholder="Insert Value.." />
<button type="button" id="btnInsert">Insert</button>
</fieldset>
<fieldset>
<legend>Local Storage</legend>
<ul id="outputList"></ul>
<br />
<button type="button" id="btnClear">Clear</button>
</fieldset>
</content>
<script type="text/javascript">
const printLSContent = function (el) {
for (let i = 0; i < localStorage.length; i++) {
let key = localStorage.key(i);
let value = localStorage.getItem(key);
let li = document.createElement('li');
li.innerHTML = `K: ${key}; V: ${value}`;
el.appendChild(li);
}
}
document.addEventListener("DOMContentLoaded", function (event) {
const inpKey = document.getElementById("inpKey");
const inpValue = document.getElementById("inpValue");
const btnInsert = document.getElementById("btnInsert");
const outputList = document.getElementById("outputList");
const btnClear = document.getElementById("btnClear");
// element.addEventListener(event, handler[, options]); // type - event type; listener - event handler; options -
btnInsert.addEventListener('click', function () {
const key = inpKey.value;
const value = inpValue.value;
localStorage.setItem(key, value);
location.reload();
}, false);
printLSContent(outputList);
// //BUTTON CLEAR
btnClear.addEventListener('click', function () {
localStorage.clear();
location.reload();
}, false);
});
</script>
</body>
</html>
Here's my current setup:
I have a barcode scanner in keyboard mode. I am trying to scan to a hidden and out of focus input.
The barcode I am trying to read is as follows: asterisk [barcode-info] asterisk.
<form method="post">
<input type="hidden" name="action" value="barcode-scan"/>
<input type="hidden" name="barcode-input" value="" id="barcode-input" onchange="this.form.submit()" />
</form>
When a barcode input is made, Javascript should capture it and update the "barcode-input" hidden input, which will then submit itself to the server.
Someone recommended trying to use a paste event listener, but it simply didn't seem to capture the input at all.
Update: because of wonderful suggestions below, I've been able to get the input working! The form will test to see if two specific inputs follow each other, then it will execute the next function. Otherwise, it will erase any information contained in the log const. Ultimately, yes, I got this working correctly!
document.addEventListener('keyup', function(e){
const log = document.getElementById('barcode-input');
log.textContent += ' ' + e.code;
document.getElementById('barcode-input').value = log.textContent;
if (log.textContent.startsWith(' ShiftLeft')) {
if (log.textContent.startsWith(' ShiftLeft Backslash')) {
document.getElementById('barcode-input').form.submit();
console.log('e.code, submit barcode info');
}
}
else {
log.textContent = '';
document.getElementById('barcode-input').value = '';
}
});
Without an input[type="text"] element on the screen, you will need to capture the keyboard input manually. Something along the lines of:
document.addEventListener('keydown', (ev) => {
if (ev.ctrlKey || ev.altKey) return; // Ignore command-like keys
if (ev.key == 'Enter') {
// ...submit the content here...
} else if (ev.key == 'Space') { // I think IE needs this
document.getElementById('barcode-input').value += ' ';
} else if (ev.key.length == 1) { // A character not a key like F12 or Backspace
document.getElementById('barcode-input').value += ev.key;
}
});
That should get you most of the way...
Alternatively, rather than looking for events on the input or values of the input (*'s), define an event on the value and use the input event to simply set the value.
Once input has stopped, be it 1 second (or most likely much less) then fire off the form.
If you have to place the cursor into input, then scan. your prob only option is to use autofocus attribute and hide the input as you cant focus a hidden element, though you also cant focus multiple so keep that in mind if you're looking to scan into multiple inputs, then you will have to show the inputs, no way around it.
For example
let elm = document.querySelector('input[name="barcode-input"]')
// watcher on the value, after 1 second, it invokes an event, i.e post form
let timer = 0
Object.defineProperty(window, 'barcode', {
get: function () { return this.value },
set: function (value) {
clearTimeout(timer)
this.value = value
timer = setTimeout(() => {
console.log('Post form')
}, 1000) // do some tests, tweak if much less then 1 second to input the value
}
})
// it should trigger input even if its a keyboard
elm.addEventListener("input", e => barcode = e.target.value)
// ignore, below this line..
// set a value of barcode at intervals, only when its stopped entering (>1 second), then will it fire the callback
let i = 0
let t = setInterval(() => {
barcode = (barcode || '')+"X"
if (i >= 40) clearInterval(t)
i++
}, 100)
// ignore... grab value from hidden input, put in #current
setInterval(() => document.querySelector('#current').innerHTML = barcode, 1000)
<input type="text" name="barcode-input" autofocus style="display:none" />
<div id="current"></div>
Here's demonstrator using keypress that scans the incoming key stream for *[ and captures the barcode until it sees ]*. Then it sends the code to the server. Although I've reproduced the form in your HTML, the code here doesn't use it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
Working...
<form method="post">
<input type="hidden" name="action" value="barcode-scan"/>
<input type="hidden" name="barcode-input" value="" id="barcode-input" onchange="this.form.submit()" />
</form>
<p id="response"></p>
<script>
(function(){
"use strict";
const bcAst = '*';
const bcLeft = '[' ;
const bcRight = ']';
let barcodeIncoming = false;
let lastChar = 0;
let barcode = '';
document.addEventListener('keypress', function(e){
function sendCode(barcode) {
console.log(barcode);
let fd = new FormData();
fd.append('barcode', barcode);
fetch('myFile.php', {
method: 'POST',
body: fd
})
.then(resp=>{
resp.text().then(txt=>{document.getElementById('response').innerText = txt;})
});
}
console.log(e.key);
switch (e.key) {
case bcAst:
if (barcodeIncoming && (lastChar === bcRight)) {
barcodeIncoming = false;
sendCode(barcode);
}
break;
case (bcLeft):
if (lastChar === bcAst) {
barcodeIncoming = true;
barcode = '';
}
break;
case (bcRight):
break;
default:
barcode += (barcodeIncoming)?e.key:'';
break;
}
lastChar = e.key;
});
})();
</script>
</body>
</html>
The current server file is very rudimetary, but serves the purpose here:
<?php
if (isset($_POST['barcode'])) {
echo "Your barcode is {$_POST['barcode']}";
} else {
echo "No barcode found";
}
Note - this has had only basic testing. You'll want to improve its resilience against possible collisions with similar data in the key stream.
transfrom
<input type="hidden" name="barcode-input" value="" id="barcode-input" onchange="this.form.submit()" />
in
<input type="test" name="barcode-input" value="" id="barcode-input" onchange="this.form.submit()" style="display:none;" />
I need to create a manual input counter using app script editor.
I've already have my website design with a single input textbox, reset button and a disabled box.
What I want is when I input a number in the textbox and press 'Enter' it will be displayed in the disabled box.If I repeat the process the new number in the textbox will sum up to the value inside the disabled box.
I would also like to have a reset button for the disabled box.
Lastly, having a record log of values inside the disabled box.
I really need to finish this before this month ends.
Is this even possible to make by just using html, Javascript and app script?
Here's my code:
let box1 = document.getElementById("box1");
let box2 = document.getElementById("box2");
let resetBtn = document.getElementById("reset");
let historyContainer = document.getElementById("history");
let history = [];
//listen key enter press on the input
box1.addEventListener("keyup", e => {
if (e.key === "Enter" && e.target.value !== "") {
box2.value = e.target.value;
history.unshift(e.target.value);
historyContainer.innerHTML += `<p>${e.target.value}</p>`;
}
});
//reset the second box and
resetBtn.addEventListener("click", () => {
box2.value = "";
});
I've used this code and apparently when the disabled box has a value and I try to enter a new number inside the input box it just merged with the value inside the disabled box, the new value must sum up to the value inside the disabled box. Also, the history log record all values entered in the textbox and not the previous value in the disabled box.
How can I fix this?
Please someone help me 😔😔
You just need to convert datatype to number using parseFloat or number:
box2.value = Number(box2.value) + Number(e.target.value);
Live example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<div>
<p>
<input id="box1" type="number" />
<input id="box2" type="number" disabled />
<button id="reset">Reset</button>
<div id="history">History</div>
</p>
</div>
<script charset="utf-8">
let box1 = document.getElementById('box1');
let box2 = document.getElementById('box2');
let resetBtn = document.getElementById('reset');
let historyContainer = document.getElementById('history');
let history = [];
//listen key enter press on the input
box1.addEventListener('keyup', e => {
if (e.key === 'Enter' && e.target.value !== '') {
box2.value = Number(box2.value)+ Number(e.target.value);
history.unshift(e.target.value);
historyContainer.innerHTML += `<p>${e.target.value}</p>`;
}
});
//reset the second box and
resetBtn.addEventListener('click', () => {
box2.value = '';
});
</script>
</body>
</html>
I'm trying to write a program so that once the user clicks the 'Add!' button, the string that they typed will be added to an initially empty array in an object, and then that updated array will be displayed back on the HTML page. However, when I checked what the value of the items array was when I typed something in, it still appeared to be null. I'm fairly certain that the addItem function is fine, is the problem in the updateList function?
HTML CODE:
<!DOCTYPE html>
<html>
<head>
<title>Homework 5</title>
<!--<link rel="stylesheet" type="text/css" href="index.css">-->
<script src="toDoList.js"></script>
</head>
<body>
<h1>Homework 5: JS Objects & HTML DOM</h1>
<div id="input">
<input id="userInput" type="text" placeholder="Type a word">
<button id="submit">Add</button>
</div>
<div id="output"></div>
<h1>Design</h1>
<h1>Challenges</h1>
</body>
</html>
JAVASCRIPT CODE:
var button = document.getElementById("submit");
var toDoList = {
items: [],
add: addItem,
update: updateList
};
function addItem(string) {
toDoList.items.push(string);
}
function updateList() {
var output = document.getElementById("output");
output.innerHTML = toDoList.items;
}
function getInput() {
var input = document.getElementById("userInput").value;
toDoList.add(input);
toDoList.update();
//clearing the text field for next use
document.getElementById("userInput").innerHTML = "";
}
button.addEventListener('click', getInput());
The second argument provided to addEventListener needs to be a function. If you put a function invocation there, that function is executed immediately, with its return value assigned as the handler. But if the return value isn't a function, the event listener doesn't work.
In your case, you just want getInput to be run when the button is clicked - getInput is not a higher-order function, so just pass the function itself, rather than invoking it:
button.addEventListener('click', getInput);
Like this
var button = document.getElementById("submit");
var toDoList = {
items: [],
add: addItem,
update: updateList
};
function addItem(string) {
toDoList.items.push(string);
}
function updateList() {
var output = document.getElementById("output");
output.innerHTML = toDoList.items;
}
function getInput() {
var input = document.getElementById("userInput").value;
toDoList.add(input);
toDoList.update();
//clearing the text field for next use
document.getElementById("userInput").innerHTML = "";
}
button.addEventListener('click', getInput);
<h1>Homework 5: JS Objects & HTML DOM</h1>
<div id="input">
<input id="userInput" type="text" placeholder="Type a word">
<button id="submit">Add</button>
</div>
<div id="output"></div>
<h1>Design</h1>
<h1>Challenges</h1>
You should not invoke or execute the function in addEventListener. Invoking function causes the function to execute immediately not when the event (click) happens. So remove parenthesis after the function name.
Change button.addEventListener('click', getInput());
To
button.addEventListener('click', getInput);
var button = document.getElementById("submit");
var toDoList = {
items: [],
add: addItem,
update: updateList
};
function addItem(string) {
toDoList.items.push(string);
}
function updateList() {
var output = document.getElementById("output");
output.innerHTML = toDoList.items;
}
function getInput() {
var input = document.getElementById("userInput").value;
toDoList.add(input);
toDoList.update();
//clearing the text field for next use
document.getElementById("userInput").innerHTML = "";
}
button.addEventListener('click', getInput);
<h1>Homework 5: JS Objects & HTML DOM</h1>
<div id="input">
<input id="userInput" type="text" placeholder="Type a word">
<button id="submit">Add</button>
</div>
<div id="output"></div>
<h1>Design</h1>
<h1>Challenges</h1>
I think, you have to loop through your array. to get the content:
var x = ['apple','banana','orange'];
var output = "";
for (i=0;i<x.length;i++) {
output += x[i];
}
alert(output); //--> outputs applebananaorange
alert(x.items); //--> undefined (whats your case)