getting a value of HTML - javascript

Im learning JavaScript and Im having problems trying to get the value of HTML of textareaElement. Theres lots online and because of all the information available its making it more confusing. I understand the idea behind the DOM, but not sure how to do the code. I am also trying to use add an event listener to store data in local storage, but without any luck.
// Add a text entry to the page
function addTextEntry(key, text, isNewEntry) {
// Create a textarea element to edit the entry
var textareaElement = document.createElement("TEXTAREA");
textareaElement.rows = 5;
textareaElement.placeholder = "(new entry)";
// Set the textarea's value to the given text (if any)
textareaElement.value = text;
// Add a section to the page containing the textarea
addSection(key, textareaElement);
// If this is a new entry (added by the user clicking a button)
// move the focus to the textarea to encourage typing
if (isNewEntry) {
textareaElement.focus();
// Get HTML input values
var data = textareaElement.value;
}
// ...get the textarea element's current value
var data = textareaElement.value;
// ...make a text item using the value
var item = makeItem("text", data);
// ...store the item in local storage using key
localStorage.setItem(key, item);
// Connect the event listener to the textarea element:
textareaElement.addEventListener('onblur', addTextEntry);
}
HTML is:
<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>
[HTML][1]

'textareaElements' is not plural as you have it here:
var data = textareaElements.value;
This is the correct form:
var data = textareaElement.value;

Related

How to add more data into LocalStorage instead of overwriting it in contenteditable attribute?

I want to create contenteditable in div when user add something in it then it should add in local storage. but right now it is overwrite when add another data.
HTMl code
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="checkEdits()">
<div id="edit" contenteditable="true">
Here is the element's original content
</div>
<input type="button" value="save my edits" onclick="saveEdits()" />
<div id="update"> - Edit the text and click to save for next time</div>
<h1 contentEditable="true">Your Name</h1>
<script src="script.js"></script>
</body>
</html>
JS code
function saveEdits() {
//get the editable element
var editElem = document.getElementById("edit");
//get the edited element content
var userVersion = editElem.innerHTML;
//save the content to local storage
localStorage.userEdits = userVersion;
//write a confirmation to the user
document.getElementById("update").innerHTML = "Edits saved!";
}
function checkEdits() {
//find out if the user has previously saved edits
if (localStorage.userEdits != null)
document.getElementById("edit").innerHTML = localStorage.userEdits;
}
You need to change your saveEdits function to check is there anything saved on storage with the same key or not. To achieve it I will recommend you to use get and set item from API here some example how you can do it.
function saveEdits() {
//get the editable element
var editElem = document.getElementById("edit");
//get the edited element content
var userVersion = editElem.innerHTML;
//get previously saved
const previousEditsStr = localstorage.getItem('userEdits');
// parse allready saved edits or create empty array
const savedEdits = previousEditsStr ? JSON.parse(previousEditsStr) : [];
// push the latest one
savedEdits.push(userVersion);
//stringify and save the content to local storage
localStorage.setItem('userEdits', JSON.stringify(savedEdits));
//write a confirmation to the user
document.getElementById("update").innerHTML = "Edits saved!";
}
Please be noticed that the memory here is limited and you need to take it under your control. For example you can limit previously saved comments.
Since we are saving an array thats men you need to change your reading part as well
function checkEdits() {
const userEdits = localStorage.getItem('userEdits');
//find out if the user has previously saved edits
if (userEdits) {
// here is the saved edits
const comments = JSON.parse(userEdits);
// showing previously saved message
document.getElementById("edit").innerHTML = comments[comments.length - 1];
}
}

How to get data from Local storage onClick in javascript

How to use the data from local storage in javascript onClick. I have my html file and javascript file below. Thanks
<fieldset>
<form>
<!--GET USER NAME-->
<p>
<label for="inName" >What is your name?</label>
<input type="text" id="inName" name="f_name"/>
</p>
<!-- GET COLOUR--> // I m not sure about how the get color as user can
//choose the color from drop down color palet.
<p>
<label for="inColor" >What is your favourite colour? </label>
<input type="color" id="inColor" name="f_color" />
</p>
<p> // how to get the value when user clicks the button
// in order to call onClick function to output the
user's name and
// display favorite color in background.
<input type="submit" value="Click to save" />
<p/>
</fieldset>
</form>
I don't know how to get data from local storage when user click to submit the form :
//NOW THAT WE HAVE STORED DATA ON ONE PAGE, WE CAN ACCESS IT FROM ANY PAGE ON THIS
WEBSITE.
window.onload = function(){
//GET ELEMENTS USED FOR OUTPUT
var userOut = document.getElementById("newMsgBox");
//GET VALUES FROM COOKIES/LOCAL STORAGE
var userName = localStorage.getItem("nameIn");
var userColor = localStorage.getItem("inColor");
//CREATE OUTPUT WITH VALUES
if (userName !== null) {
userOut.innerHTML = " " +userName;
}
}//end onload
If you want to listener event from an specific button and then access to your localStorage you could do this:
first get the element:
const button = document.getElementById('<clickable_element_id>');
then add a listener to the button;
button.addEventListener("click",(event)=> {
event.preventDefault() // only if you want to prevent the action
//here you can access to your local store items like:
const a = localStorage.getItem("<item you saved previously>");
...
});
It's really unclear what you want to do but
let inColor = document.getElementById('inColor');
let inName = document.getElementById('inColor');
Will fetch the values for you.
I think you are looking for something like this.
<script>
function saveData() {
let inColor = document.getElementById('inColor');
let inName = document.getElementById('inName');
localStorage.setItem("inColor", inColor);
localStorage.setItem("inName", inName);
}
</script>
<input type="Button" value="Click to save" onclick="saveData"/>
Import Jquery and use this. I hope help you. when you click on button with id idOfBtn jquery gonna eject the event and call the localStorage with key (key). Replace it for you key name.
$("#idOfBtn").click(function() {
alert(localStorage.getItem('_key_'));
});

How to get input value and replace part of p-tag with the value using JS?

I want the to get the input value and for it to replace a part of the P tag text.
Please see my code below:
<input class="cyberpunk mt-3" id="strangers-name" placeholder="Nickname" type="text" onblur="getStrangerName()"/>
<p id="welcome-stranger-note">Welcome, stranger</p>
<script>
function getStrangerName() {
const user = document.getElementById('strangers-name').value;
document.write("Welcome, " + user);
}
</script>
What I'm hoping to achieve is, if a user entered their nickname in the input, it will replace the default text inside the paragraph tag from "Welcome, stranger" to "Welcome, (insert user input)"
Right now, it's replacing the whole document instead of just the p tags.
Extra question (if possible): How do I store the user's input into the local storage so on their next visit, their name will still be there in the replaced paragraph text?
Thank you in advance! I'm just learning JS..
Write a function to set the text in the paragraph
Get the value from localStorage and if it exists, set the text
Add a change event listener to handle the user input that can set the paragraph text and save the value into local storage
// fake localStorage for snippet sandbox, just ignore
// and definitely don't include it in your code
const localStorage={getItem(...args){console.log("localStorage.getItem",...args)},setItem(...args){console.log("localStorage.setItem",...args)}}
// Storage key name
const STORAGE_KEY = "nickname";
// Grab a reference to the <p> element
const welcome = document.getElementById("welcome-stranger-note");
// Sets the text within the welcome element
const setNickname = (name) => {
// See https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
welcome.textContent = `Welcome, ${name ?? "stranger"}`
}
// Add a "change" event listener
document.getElementById("strangers-name").addEventListener("change", e => {
const nickname = e.target.value.trim();
// Only set if not empty
if (nickname) {
setNickname(nickname);
localStorage.setItem(STORAGE_KEY, nickname);
}
});
// Call setNickname with value from localStorage
setNickname(localStorage.getItem(STORAGE_KEY));
<input id="strangers-name" placeholder="Nickname" />
<p id="welcome-stranger-note"></p>

How to addEventListener to an html element if the element is pushed to the html through this js file?

I pushed a <form> to the HTML file by JS file, and then addEventListener to this form but an error turns out:
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener').
I assume that is because this JS file is linked directly to the HTML file which means the JS might be loaded before the <form>.
Can anyone please tell me how to resolve this?
The JS codes are below:
// skip to the input fields
$start.addEventListener('click', function(){
$chooseStory.remove()
const inputs = []
inputs.push(`
<form id="form">
<label>Provide The Following Words</lable>
`)
// assign words of stories to names and placeholders of inputs
// the input will automatically loop for as many as the words are
for (const word of stories[$index.value].words) {
inputs.push(`
<input type="text" name='${word}' placeholder="${word}">
`)}
inputs.push(`
<button type="submit" id="submit"> Read Story </button>
<code id="result"></code>
</form>
`)
const inputsField = inputs.join('')
$container.innerHTML += inputsField
})
// retrieve value of the form
const $form = document.getElementById('form')
$form.addEventListener('submit', function(e){
e.preventDefault()
})
You need to use event delegation wherein a listener is attached to a parent component which captures events from child elements as they "bubble up" the DOM.
// Adds a new form to the page
function addForm() {
const html = `
<form id="form">
<label>Provide The Following Words</lable>
<input />
<button type="submit" id="submit">Read Story</button>
<code id="result"></code>
</form>
`;
// Add the new HTML to the container
container.insertAdjacentHTML('beforeend', html);
}
function handleClick(e) {
// In this example we just want to
// to log the input value to the console
// so we first prevent the form from submitting
e.preventDefault();
// Get the id of the submitted form and
// use that to get the input element
// Then we log the input value
const { id } = e.target;
const input = document.querySelector(`#${id} input`);
console.log(input.value);
}
// Cache the container, and add the listener to it
const container = document.querySelector('#container');
container.addEventListener('submit', handleClick, false);
// Add the form to the DOM
addForm();
<div id="container"></div>

Move the check mark in MacOS dropdown

I made a drop down list using the <select> and <option> tag, where every time a new input is typed, the program creates a new option tag with value attribute to add it to the existing options in the drop down list.
However, my client uses a MacOS and he wanted to move the check mark on the drop down list to the recently added option. The check mark only moves when you click on the selected line, but in my case, I want it to also move to the recently added/typed data.
Here is the HTML code:
<!-- Created select tag so user can access history of talk -->
<div style="top:60px;position:absolute;z-index:2" id="speechBox">
<!-- The select tag acts like a drop down button, so it passes its value to the input box and not to itself -->
<select id = 'combo-box' title = "Saved Talk" onchange="document.getElementById('userText').value=this.options[this.selectedIndex].text; document.getElementById('idValue').value=this.options[this.selectedIndex].value;">
</select>
<span class = "dropdown" name = "Saved Talk"></span>
<input id ="userText" name="userText" type="text" onfocus="this.select()" ></input>
<input name="idValue" id="idValue" type="hidden">
<button id="speakText" class="toolbutton" title="Speak"></button>
<hr>
</div>
And the JS:
hiddenArray(); // Access speakArray
// Function containing the speakArray, which saves the recent talk array
function hiddenArray() {
speakArray = [];
}
function playVoice(language, text) {
playing = text;
//Adds option when text is spoken
var addUserInput = document.createElement("OPTION");
addUserInput.setAttribute("value", playing);
addUserInput.text = playing;
document.getElementById("combo-box").appendChild(addUserInput);
speakArray.push(playing); // Adds recent talks to speakArray
if(document.getElementById('mode').innerHTML=="2"){
//After the voice is loaded, playSound callback is called
getBotReply(text);
setTimeout(function(){
loadVoice(language, playSound);
}, 4000);
}
else{
loadVoice(language, playSound);
}
}
I've figured it out in the end. Here is the code:
hiddenArray(); // Access speakArray
// Function containing the speakArray, which saves the recent talk array
function hiddenArray() {
speakArray = [];
}
function playVoice(language, text) {
playing = text;
//Adds option when text is spoken
var addUserInput = document.createElement("OPTION");
addUserInput.setAttribute("value", playing);
addUserInput.text = playing;
document.getElementById("combo-box").appendChild(addUserInput);
document.getElementById("combo-box").value = playing;
speakArray.push(playing); // Adds recent talks to speakArray
if(document.getElementById('mode').innerHTML=="2"){
//After the voice is loaded, playSound callback is called
getBotReply(text);
setTimeout(function(){
loadVoice(language, playSound);
}, 4000);
}
else{
loadVoice(language, playSound);
}
}
So what I did here is asign the value of the combo box (select tag) to the recently added option (variable playing).

Categories

Resources