issue detecting text box contents and converting to local storage [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
// Create an event listener to save the entry when it changes
// (i.e. when the user types into the textarea)
function saveEntry() {
// TODO: Q1(c)(iii) Task 1 of 2
// Save the text entry:
// ...get the textarea element's current value
// (getting HTML input values is in Block 2 Part 2 Section 6)
document.getElementById("addTextEntry").value.addEventListener("click", localStorage);
// ...make a text item using the value
// (demonstrated elsewhere in this file)
// ...store the item in local storage using the given key
// (local storage is in Block 3 Part 5)
localStorage.setItem(key, JSON.item);
}
I can't get the text area element to store into local storage can anyone give any pointers as I am at a standstill and scratching my head.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>My Erehwon Diary NOTCODE123</title>
<meta name="author" content="Stephen Rice" />
<!-- Set viewport to ensure this page scales correctly on mobile devices -
->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="tma03.css" />
<!-- Set demo data -->
<script src="tma03-demo.js"></script>
<!-- Start TMA03 application -->
<script src="tma03.js"></script>
</head>
<body>
<h1>My Erehwon Diary NOTCODE123</h1>
<main>
<section id="text" class="button">
<button type="button">Add entry</button>
</section>
<section id="image" class="button">
<button type="button">Add photo</button>
<input type="file" accept="image/*" />
</section>
</main>
</body>
<script type="text/javascript">
localStorage.removeItem("")
</script>
</html>
this is the HTML if anyone needs more info please let me know I have tried some of the code people have sent and nothing is working as of yet and tank you in advance

You're setting your click event to call localStorage, but there is no localStorage function.
Without seeing your HTML I think what you're trying to do is something like this:
document.getElementById("addTextEntry").addEventListener("click", saveEntry);
function saveEntry(e) {
const addTextEntryEl = e.currentTarget.value;
// You will need to add code here to do what you want and then call your local storage below with the right parameters you're setting up here
localStorage.setItem(key, JSON.item);
}

Your event listener is a bit off. This is how you can add an event listener to a textarea (note the input event listener):
document.getElementsByClassName("add-text-entry")[0].addEventListener("input", function(event) {
console.clear();
console.log(event.target.value);
})
<textarea class="add-text-entry"></textarea>
You can simply replace the console statements with localStorage.setItem(key, value.);

Make sure you are correctly getting the value of the textbox. It should already be a string, so there is no need to process it further with JSON methods:
const value = document.getElementById("addTextEntry").value;
localStorage.setItem(key, value);

.addEventListener takes in the event type and a listener. A listener is a function. localStorage is not a function. JSON.item is also invalid.
document.getElementById("addTextEntry").addEventListener("click", function() {
var item = document.getElementById("addTextEntry").value;
localStorage.setItem(key, item);
});
You can read more about addEventListener and localStorage.

Related

I'm trying to get the value of the input to the label field in the QR generator code but not sure where I'm going wrong?

Trying to make a dynamic change along with the input that we type, there is a change in the input field .
Or
Once we submit the input, we get a change in the label?
How can we approach it? I am trying to pass the input value but something is wrong
$(document).ready(function(){
// $(".demo").qrcode({
// text: 'https://www.jqueryscript.net'
// });
var input = document.querySelector('.input');
var data = input.value;
$(".demo").qrcode({
// 0: normal
// 1: label strip
// 2: label box
mode: 1,
label: "{{name}}",
fontname: 'sans',
fontcolor: '#000'
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://unpkg.com/browse/qrcode#1.2.0/build/qrcode.min.js"></script>
<!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>Document</title>
</head>
<body>
<input type="text" class="input ng-model='name'">
<div class="demo">
</div>
</body>
</html>
You didn't link to the QR lib you are using (and AFAICT someone else's edit of your question confused things even more by linking to a different, wrong QR lib) which makes things harder. My guess is you are using jQuery.qrcode. For future reference you will make it easier for people to help you if you can clearly state what you are using, and create a minimal, complete, and verifiable example - working, complete code which demonstrates your problem.
Next problem is you are using an ancient version of jQuery (1.12.4). Is there a reason for that? Whatever the reason, jQuery.qrcode does not work with that version of jQuery. I tried jQuery 3.3.1, the latest version Stackoverflow snippets list, but that doesn't work either. Finally I checked the demo linked from the jQuery.qrcode home page, viewed that source, and found they are using 3.5.1. And using that version in my snippet works!
So, now we finally have a working set of libraries, on to the actual question.
If you want to update the label dynamically, as you type, you'll need to add an event listener. You could use the change() event, but for a text input that will fire only after you click away or hit enter - so you won't see live typing cause any updates. If you want to see the label update live, as you type, keyup() is the way to go, and I've used that below.
Your handler just needs to
Get the current text;
Remove the old QR code, otherwise you end up with one for each keypress on the page;
Draw a new QR code with that new label;
Here's a working snippet - click Run to see it in action.
$(document).ready(function(){
// The link "content" of the QR code, the actual message
var text = 'https://stackoverflow.com/q/71073404/6089612';
var demo = $('.demo');
var input = $('.input');
// Simple function to draw the QR code with the specified label
function drawQR(label) {
$(".demo").qrcode({
mode: 1,
label: label,
text: text,
fontname: 'sans',
fontcolor: '#000'
});
}
// Define an event handler that will fire every time a key is typed
// in your input
input.on('keyup', function() {
// First get the current label text
var label = $(this).val();
// Now remove the existing QR code by emptying the div content
demo.html('');
// Finally redraw the QR with our new label
drawQR(label);
});
});
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lrsjng.jquery-qrcode/0.18.0/jquery-qrcode.min.js"></script>
Label: <input type="text" class="input ng-model='name'">
<div class="demo"></div>

Javascript want to have a label that you can check for auto-refreshing the page [duplicate]

This question already has answers here:
Javascript Auto Refresh Toggle Checkbox
(3 answers)
How to reload page every 5 seconds?
(11 answers)
Closed 2 years ago.
I have tried to make a label, that when you 'check' it, it will auto-refresh the page every 5 seconds. I found a few threads but didn't get it to work! this is how I have done it so far:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<label>
<input
type="checkbox"
name="refresh"
autocomplete="off"
value="autorefreshoff"
id="refresh-btn"
onclick="refresh()"
/>
</label>
</body>
<script>
//Don't know what do do here, tried this:
function refresh() {
window.location.reload(1);
}
</script>
</html>
I am guessing that I have to make a loop in my javascript code with a delay on? So whenever this label is "checked" its gonna loop through the javascript code every 5 seconds, and if I would turn off the label its gonna stop looping.
Don't know javascript that well unfortunately.
Here's a basic example of how to load data every second using fetch, then updating the DOM. You need to adapt this to your needs.
setInterval(fetchNewData, 1000);
fetchNewData();
function fetchNewData() {
fetch('https://jsonplaceholder.typicode.com/todos/' + Math.floor(Math.random() * 10) + 1)
.then(r => r.json())
.then(r => document.getElementById('foo').innerHTML = `User title: ${r.title}`);
}
<div id="foo">
</div>
I think this is what you are looking for:
Javascript Auto Refresh Toggle Checkbox
Pls approve this answer if it was helpful!

Javascript ES6: setting <h1> with local storage and form submission

I am trying to set the element #welcome_banner by using a function in javascript that takes a form submission and sets it to localStorage and then pulls that info and sets it onto an <h1> tag. Apparently it works but only changes the tag for a millisecond and then it disappears! I have tried doing the .innerHTML setting in various places inside and outside of the function clickHandler() and in the main body of the script. I am certain this is something superbasic I am missing.
<!DOCTYPE html>
<html>
<head>
</head>
<script >
//set display name to form submission, set welcome banner to display name
function clickHandler () {
document.querySelector('#display_name').onsubmit = function() {
localStorage.setItem('dn', dn);
document.querySelector('#welcome_banner').innerHTML=changeWelcomeBanner;
}
};
function changeWelcomeBanner () {
var dn = localStorage.getItem('#dn').value;
var welcomeBanner = document.getElementById('#welcome_banner');
welcomBanner.innerHTML = `Hello ${dn}`;
}
</script>
<title>Project 2</title>
<body style="background-color:#ff3300;">
<h1 id="welcome_banner"></h1>
<form id="display_name">
<input id="dn" autocomplete="off" autofocus placeholder="" type="text">
<button>set display name</button>
</body>
</html>
The steps to do this are as follows:
Store the typed text in localStorage, you're doing this in the event handler for the form submission: localStorage.setItem('dn', dn);
When you submit the form, the page is going to refresh from the server. This is why you're only seeing the text briefly, then the page reloads from the server with no knowledge of what was there before.
Look for information about page events and write a handler for the DOMContentLoaded event like you did for your submit event handler. DOMContentLoaded is well supported these days. Something like: document.addEventListener("DOMContentLoaded", function(event) {
// code to check local storage goes here...
});
In that handler you want to check localStorage like you're doing here: var dn = localStorage.getItem('dn').value; and if there is a value there, set the innerHtml of the <h1> to that value, like you're doing here: welcomBanner.innerHTML = 'Hello ${dn}';
I think you might have had a stray # character in your localStorage.getItem call that I removed in the steps above. You might also want to have default text you post if there's nothing found in localStorage when you check.
Here's a simplified example:
If you are calling a function to get the value from Local Storage, be sure you have a return
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1 id="welcome"></h1>
<input type="text" id="something">
<button type="button" id="click">CLICK ME</button>
<script>
document.getElementById("click").addEventListener("click", function(){
var x=document.getElementById("something").value;
document.getElementById("welcome").innerHTML=x;
localStorage.setItem('x', JSON.stringify(x));
document.getElementById("welcome").innerHTML = getData();
});
function getData(){
var retrieve=localStorage.getItem('x');
return JSON.parse(retrieve); //Now return the value
}
</script>
</body>
</html>

How can I make a JavaScript function wait for input or value?

As you can see below, I have a function,createCharacter(), that calls another function, getUserInput(). This function is intended to grab the value of a text input element and return that value to be stored in the "name" variable within the createCharacter. However, if you run this code. It completely runs through both functions, never giving the opportunity for the user to input a value. Perhaps a more specific question is, how can I make this function wait for the variable to be defined before returning it to createCharacter? I've tried to wrap the code in a while loop that will run for as long as value is undefined. Didn't work, created an infinite loop and crashed. ANY solution to this problem will be greatly appreciated. I feel like the solution is so simple, but I just can't figure it out for the life of me. Thanks.
var messageDisplay = document.querySelector(".message-display");
var menuInput = document.querySelector(".menu-input");
var playerInput = document.querySelector(".player-text")
function createCharacter() {
messageDisplay.textContent = "Welcome! What is your name?";
var name = getUserInput();
messageDisplay.textContent = "Hello " + name + "!";
}
function getUserInput() {
var textValue = playerInput.value;
return textValue;
}
createCharacter();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="message-display"></div>
<div class="menu-input">
<form class="menu-input-content">
<input class="player-text" type="text">
<input class="submit-button" type="submit">
</form>
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
I think you have a misunderstanding of how the DOM and the user interact. The DOM is event based. You can start by add an change event listener to your input element (or on the submit button):
menuInput.onchange = createCharacter;
And then remove the call to createCharacter, the last line in the code you posted.
This will then call the createCharacter() method when you change the text in the input at all, which is probably not what you want. You could also try:
var menuSubmit = document.querySelector(".submit-button");
menuSubmit.onclick = createCharacter;
And that is probably more on the right track.
However, given your misunderstanding in the first place, perhaps you need to reconsider how you approach your design?
The reason it runs through the code immediately is because of the last line. The browser loads the JS and executes everything in the global scope. Your query selectors are run and stored in those variables, the functions defined, and then on the last line you call one of the defined functions.
To fix this you need to redesign your app to be event based. Keep defining needed variables and functions in the global scope, as you are doing here, but then change your execution to be in response to events.
I think you are looking for something like this. You should be using the events to get what you wanted. You are executing createCharacter() before even the user clicked the Submit button. Hence you see "Hello !" as there is no user input initially.
function submitClicked(event) {
var messageDisplay = document.querySelector(".message-display");
var playerInput = document.querySelector(".player-text");
messageDisplay.innerHTML = "Hello " + playerInput.value;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="message-display"></div>
<div class="menu-input">
<input class="player-text" type="text">
<input class="submit-button" onclick="submitClicked()" type="submit">
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>

To Do list in HTML/Javascript/jQuery [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to make a to do list in Javascript / HTML5. Here's my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To Do </title>
<link rel="stylesheet" href="todolist.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="To Do.js"></script>
</head>
<body>
<div id="list">
</div>
<form id="to_do_list">
<h2>What do you want to do? </h2>
<input type="text" id="task" name="task"><br>
<br/>
<button type="button" id="addToList"> Add to List </button> <br/>
</form>
</body>
</html>
I'm trying to figure out how to work Javascript that will form a list with the user's entries.
Sorry if this is easy, I am new to this.
JavaScript
window.onload = function () {
$("addToList").onclick = addTask;
}
var addTask = function() {
alert("You clicked it!");
}
You need to decide whether to use JQuery or Javascript for your script section.
It looks you have used Javascript, then switched to JQuery to reference an object then went back to Javascript. Try to stick to just one.
<script>
// this could be $(window).ready(function() { ...
window.onload = function () {
$("#addToList").click(addTask); // you need to point at the id #addToList
}
var addTask = function() {
var task = $("#task").val(); // references the value inside #task
$("#list").append("<p>"+task+"</p>") // makes a new <p> element
$("#task").val(""); // empties out #task
}
</script>
I'm not really sure what you're looking for, but this does what I think you want.
Also, I don't think you should use spaces in filenames ("To do.js")

Categories