I created a form to collect user information and then saved it in localstorage.
To finish the programming I want to display this information in an HTML page. However, the way I did the information appears and disappears quickly.
<!DOCTYPE html>
<html>
<body>
<form style="width:50%; margin-left: 20%; margin-top: 1.9%;">
<div class="form-group mx-sm-3 mb-2">
<h2 style="font-size: 1.0rem;">Selecione a data</h2>
<input id="datepicker" width="396" />
<div class="input-group mb-3">
<input type="text" class="form-control" id="matriz" aria-label="Amount (to the nearest dollar)">
<div class="input-group-append">
<span class="input-group-text">Matriz</span>
</div>
</div>
<div class="input-group mb-3">
<input type="text" class="form-control" id="rep" aria-label="Amount (to the nearest dollar)">
<div class="input-group-append">
<span class="input-group-text">Rep</span>
</div>
</div>
<p>Saved info is:</p>
<p id="currentDate"></p>
<p id="currentRep"></p>
<p id="currentMatriz"></p>
<script>
$('#datepicker').datepicker({
uiLibrary: 'bootstrap5'
});
</script>
<script>
store();
function store(){
const inputDate = document.getElementById('datepicker').value;
const inputRep = document.getElementById('rep').value;
const inputMatriz = document.getElementById('matriz').value;
window.localStorage.setItem('Date', String(inputDate));
window.localStorage.setItem("Rep", String(inputRep));
window.localStorage.setItem("Matriz", String(inputMatriz));
document.getElementById("currentDate").innerHTML = window.localStorage.getItem("Date");
document.getElementById("currentRep").innerHTML = localStorage.getItem("Rep");
document.getElementById("currentMatriz").innerHTML = localStorage.getItem("Matriz");
}
</script>
</body>
</html>
Is there any way to display the user values in html page from local storage?
You are setting the key "Rep" but then getting "Reprodutor". This might be the issue why you don't see the values appear on the page
Your code does the following steps (in order):
Read value of DOM elements
Save that value to LocalStorage
Read value from LocalStorage and inject into DOM elements
Since the DOM elements are empty on page load, you'll push 'nothing' to the LocalStorage, read 'nothing' so there's nothing to show.
Consider the following example where we change the order if needed:
store();
function store(){
// Get elements
const inputDate = document.getElementById('datepicker');
const inputRep = document.getElementById('rep');
const inputMatriz = document.getElementById('matriz');
// IF there is NOTHING in LocalStorage
if (window.localStorage.getItem('Date') === null) {
// Set dumy value so we'll not push 'empty' things to LocalStorage
inputDate.innerHTML = 'Dummy date';
inputRep.innerHTML = 'Dummy rep';
inputMatriz.innerHTML = 'Dummy Matriz';
// Save to localStorage
window.localStorage.setItem('Date', inputDate.innerHTML);
window.localStorage.setItem("Rep", inputRep.innerHTML);
window.localStorage.setItem("Matriz", inputMatriz.innerHTML);
} else {
// Set to DOM eleemnts
inputDate.innerHTML = window.localStorage.getItem("Date");
inputRep.innerHTML = localStorage.getItem("Rep");
inputMatriz.innerHTML = localStorage.getItem("Matriz");
}
}
<p>Saved info is:</p>
<p id="currentDate"></p>
<p id="currentReprodutor"></p>
<p id="currentMatriz"></p>
<hr >
<div id='datepicker'></div>
<div id='rep'></div>
<div id='matriz'></div>
Note: This does not work in SO snippets, try it offline
Related
Do you think it's possible to retrieve a text from the localStorage and display it immediately without going through a button, like below?
<div class="container">
<h1 id="h1">Hello unknown ! </h1>
<label>Name: </label>
<input type="text" id="myName">
<input type="button" value="ok" onclick="btnStorage()">
</div>
function btnStorage(){
if(localStorage.getItem("myName") != null)
h1.textContent = `Hello ${localStorage.getItem("myName")}`;
localStorage.setItem("myName", myName.value)
}
Old but gold.
<body onload="btnStorage()"></body>
I am having trouble being able to add user input data. I can get it working when I add in the data myself all the users show up in the console in the array. For people 1-3 I would like them to enter their name and favorite color but I can't seem to be able to store it or at least have it come up in the console. I did remove person 2 and 3 from the array so I can test it easier and quicker. if you were to take the
user: document.getElementById('name').value,
color: document.getElementById('color').value,
and all the comments it would work and show up in console how i want it to but cant seem to do user data. Sorry if this is confusing i am a new to javascript.
<!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>
<form>
<div class="formBox">
<label for="name">Name</label>
<input type="text" id="name" placeholder="Name"/>
</div>
<div class="formBox">
<label for="color">Favorite color</label>
<input type="text" id="color" placeholder="Color"/>
</div>
<div class="formBox">
<button id="btn">Click to Add</button>
</div>
<div id="msg">
<pre></pre>
</div>
</form>
<script >
const person1 = {
user: document.getElementById('name').value,
color: document.getElementById('color').value,
/* user: "Sarah",
color: "Yellow",*/
};
/* const person2 = {
user: "Aaron",
color: "Yellow"
};
const person3 = {
user: "Sarah",
color: "Green",
};
*/
array = [person1]
sort = array.sort(function(a, b){
if(a.user < b.user) { return -1; }
if(a.user > b.user) { return 1; }
return 0;
})
console.log(sort)
</script>
</body>
</html>
I give you a code matches with your purpose but I recommend you found a course that builds a complete project, that can helps you to understands how to use basics to build some complex things.
// Declare Part
const users = [];
const form = document.getElementById("myForm");
// 1. Add Event Listener to our form
// when form submits the function get called
form.addEventListener("submit", (event) => {
// Stop form from refreshing the page
event.preventDefault();
// Get name field value
const userName = document.getElementById("name").value;
// Get color field value
const userColor = document.getElementById("color").value;
// Create new person
const person = {
user: userName,
color: userColor,
};
// Store new person (Add new person to array of users)
users.push(person);
// Now we sort our users
users.sort(function(a, b) {
if (a.user < b.user) {
return -1;
}
if (a.user > b.user) {
return 1;
}
return 0;
});
// See the result
console.log(users);
});
<form id="myForm">
<div class="formBox">
<label for="name">Name</label>
<input type="text" id="name" placeholder="Name" />
</div>
<div class="formBox">
<label for="color">Favorite color</label>
<input type="text" id="color" placeholder="Color" />
</div>
<div class="formBox">
<button id="btn">Click to Add</button>
</div>
<div id="msg">
<pre></pre>
</div>
</form>
The javascript in your code is running start to finish every time you refresh the page and when you're clicking the click to add button, you're submitting the form, which automatically refreshes the page. You can make a couple of tweaks in your code to fix this...
You can add type="button" as a property of your button to tell the browser that this is a button and not a way of submitting your form. By doing this your page wont refresh when you click it.
You want your javascript code to run when you click the button, not when the page loads. To do this you need to wrap it in a function and add an onclick handler to your button that executes the function when the button is clicked. You'll notice the array is initialised outside the function, this is because we do want the array to be initialised when you load the page, and not when the button is clicked, otherwise we would be overwriting the array every time we added something to it.
const array = []
const addUser = () => {
const person1 = {
user: document.getElementById('name').value,
color: document.getElementById('color').value,
};
array.push(person1)
sort = array.sort(function(a, b){
if(a.user < b.user) { return -1; }
if(a.user > b.user) { return 1; }
return 0;
})
console.log(sort)
}
<form>
<div class="formBox">
<label for="name">Name</label>
<input type="text" id="name" placeholder="Name"/>
</div>
<div class="formBox">
<label for="color">Favorite color</label>
<input type="text" id="color" placeholder="Color"/>
</div>
<div class="formBox">
<button
id="btn"
type="button"
onclick="addUser(this)"
>Click to Add</button>
</div>
<div id="msg">
<pre></pre>
</div>
</form>
I am new to google scripting. I have followed some tutorials online and created a user form which has 4 input:
company name, qty, agent and comment. The only goal here is to copy data from user form to spread sheet. I have written the following html and functions but data does not get populated after button add is clicked.
I know the addRowData function is working when correct input gets to it. So either I am not population rowData correctly or EventListener does not work correctly. Can anybody please help me find where the issue is?
function addNewRow(rowData) {
const currentDate=new Date();
const ss=SpreadsheetApp.getActiveSpreadsheet();
const ws=ss.getSheetByName("Results");
ws.appendRow([currentDate, rowData.companyName,rowData.qty,rowData.agentName,rowData.commentText]);
return true;
}
<div class="container">
<div>
<div class="form-group">
<label for="company-name">Company</label>
<input type="text" class="form-control" id="company-name">
</div>
<div class="form-group">
<label for="number-boxes">Number of Boxes</label>
<input type="Text" class="form-control" id="number-boxes">
</div>
<div class="form-group">
<label for="agent-name">Agent</label>
<input type="text" class="form-control" id="agent-name">
</div>
<div class="form-group">
<label for="comment-text">Comment</label>
<input type="Text" class="form-control" id="comment-text">
</div>
<button class="btn btn-primary" id="mainButton">Add</button>
</div>
</div>
<script>
function afterButtonClicked(){
var companyName = getElementById("company-name");
var qty = getElementById("number-boxes");
var agentName = getElementById("agent-name");
var commentText = getElementById("comment-text");
var rowData={companyName: companyName.value,qty: qty.value,agentName: agentName.value,commentText: commentText.value};
google.script.run.withSuccessHandler(afterSubmit).addNewRow(rowData);
}
function afterSubmit(e){
var qty = getElementById("number-boxes");
qty.value="";
}
document.getElementById("mainButton").addEventListener("click",afterButtonClicked());
</script>
</body>
I would like to propose the following modification.
Modification points:
At document.getElementById("mainButton").addEventListener("click",afterButtonClicked());, the function is run by () of afterButtonClicked() at the load of HTML. In this case, please remove ().
About getElementById("###"), in this case, please add document like document.getElementById("###").
When above points are reflected to your script, it becomes as follows. I think that your Google Apps Script works.
Modified script:
In this case, please modify your Javascript as follows.
<script>
function afterButtonClicked(){
var companyName = document.getElementById("company-name");
var qty = document.getElementById("number-boxes");
var agentName = document.getElementById("agent-name");
var commentText = document.getElementById("comment-text");
var rowData={companyName: companyName.value,qty: qty.value,agentName: agentName.value,commentText: commentText.value};
google.script.run.withSuccessHandler(afterSubmit).addNewRow(rowData);
}
function afterSubmit(e){
var qty = document.getElementById("number-boxes");
qty.value="";
}
document.getElementById("mainButton").addEventListener("click",afterButtonClicked);
</script>
References:
EventTarget.addEventListener()
Document.getElementById()
I have some code that successfully inputs a variety of values into a form on a webpage and I can see that the data is put into the correct fields in the correct format. When I submit the form using the 'OK' button, or code, the process completes but the Date data carried through is the current date, despite the fact that I can see a different date displayed in the field. I can cut and paste data into the field from e.g., Notepad and it works fine.
Here is the html for the beginning of the form:
<form action="#" method="get">
<div class="columns group">
<div class="formColumn flex">
<div id="editConference_ownerField" style="display: none">
<div class="formRow">
<div class="labelBlock" id="editConference_ownerLbl">Owner</div>
<div class="fieldBlock fillspace">
<select id="editConference_owner"></select>
</div>
</div>
</div>
// The first input in this class loads find and is pulled through when the form is submitted using the OK button
<div class="formRow">
<label class="labelBlock" id="editConference_labelLbl" for="editConference_label">Title</label>
<div class="fieldBlock fillspace">
<input type="text" class="input" id="editConference_label" maxlength="256" value="">
</div>
</div>
<div id="editConference_timeFields" style="">
<div class="formRow">
<div class="labelBlock" id="editConference_startLbl">Start</div>
<div class="fieldBlock calendarBlock">
<input type="date" id="editConference_startNative" class="native_date has_native">
// The element id="editConference_start" is a date and does NOT pull through
<input type="text" id="editConference_start" class="sl_date has_native" placeholder="DD/MM/YYYY">
// The element id="editConference_startTime" is a time DOES pull through!
<input type="text" id="editConference_startTime" placeholder="Time" class="ui-timepicker-input" autocomplete="off">
<div id="start-date-picker"><div class="pika-single is-hidden is-bound" style="position: static; left: auto; top: auto;"></div></div>
<div id="start-time-picker"></div>
</div>
</div>
<div class="formRow">
<div class="labelBlock" id="editConference_endLbl">End</div>
<div class="fieldBlock calendarBlock">
<input type="date" id="editConference_endNative" class="native_date has_native">
<input type="text" id="editConference_end" class="sl_date has_native" placeholder="DD/MM/YYYY">
<input type="text" id="editConference_endTime" placeholder="Time" class="ui-timepicker-input" autocomplete="off">
<div id="end-date-picker"><div class="pika-single is-hidden is-bound" style="position: static; left: auto; top: auto;"></div></div>
<div id="end-time-picker"></div>
</div>
</div>
Here is the Javascript that I have been using. I have been testing it out using the Chrome F12 Console and working inside the iframe. All the inputs used appear to be of type="text". It automates the filling out of the form except the problem noted above and submits it:
\\Loading the data into the fields
var Title = "Coding syntax test again";
document.getElementById('editConference_label').value = Title;
var StDate = "06/05/2020";
document.getElementById('editConference_start').value = StDate;
var StTime = "16:20";
document.getElementById('editConference_startTime').value = StTime;
var EndDate = "06/05/2020";
document.getElementById('editConference_end').value = EndDate;
var EndTime = "17:50";
document.getElementById('editConference_endTime').value = EndTime;
var Desc = "The conference description stuff";
document.getElementById('editConference_description').value = Desc;
\\ Click 'OK'
document.getElementById("editConference_ok").click();
Things tried:
1) Using the code below to enter data via the id ="editConference_startNative" element. It does not seem to work but I am not sure if my code makes any sense or if this something worth pursing:
var StDate = document.querySelector('input[type="date"]');
StDate.value = '2020-05-05';
document.getElementById('editConference_startNative').value = StDate;
2) Creating a var with a date type for use with the Native version of the input
var StDate = new Date("05/05/2020");
document.getElementById('editConference_startNative').value = StDate;
I think the output is in the wrong form to be used but can't figure out how to shorten it in the right format. Perhaps this is not the right approach.
3) Removing the final click code then waiting for a few seconds and them adding the Click line in and executing but this did not work so I presume it is not a question of a delay. I also tried this code before the click code for a delay but I am not sure if it is valid:
setTimeout(function(){}, 3000);
document.getElementById("editConference_ok").click();
Thanks in advance for any suggestions.
In a following code I want to access user data written in a form each time user presses an enter key after typing some text data inside an input field in chat-form. Do you have any idea how can I access the following text-data using TypeScript? I have already tried with jQuery but none of the tested code seems to work. I am new to web-dev but very eager to learn new things.
<div id="chat-container">
<div id="search-container">
<input type="text" placeholder="search" />
</div>
<div id="conversation-list">
</div>
<div id="new-message-container">
+
</div>
<div id="chat-title">
</div>
<div id="chat-message-title">
</div>
<div id="chat-form">
<input id="chat-form" type="text" placeholder="Type a message!" />
</div>
</div>
first, you should use a semantic HTML by using form tag instead of div so u can use enter key to handle the submit action. second, it is not an appropriate way to duplicate an id for two different elements because id is a unique identifier for the element. finally here is a simple form and it might be helpful.
HTML:
<form id="my-form">
<input type="text" id="my-input" />
<button type="submit" id="submit-btn">send</button>
</form>
JS:
const formEl = document.getElementById("my-form") as HTMLFormElement;
const inputEl = formEl.querySelector("my-input") as HTMLInputElement;
const submitBtnEl = formEl.querySelector("submit-btn") as HTMLButtonElement;
formEl.addEventListener("submit", e => {
e.preventDefault();
// do what you want
});
inputEl.addEventListener("change", (e:Event|any) => {
console.log(e.target.value)
// do what you want
})
Before the answer: you have duplicated id="chat-form"
<div id="chat-form">
<input id="chat-form"type="text" placeholder="Type a message!"/>
</div>
Example
// select element
const elInput: HTMLInputElement = document.querySelector(`#chat-form-input`)
// add onkeypress listener
document.onkeypress = function (e: any) {
// use e.keyCode
if (e.key === 'Enter') {
// code for enter
console.log(elInput)
console.log(elInput.value)
}
}
<body>
<div id="chat-container">
<div id="search-container">
<input type="text" placeholder="search"/>
</div>
<div id="conversation-list">
</div>
<div id="new-message-container">
+
</div>
<div id="chat-title">
</div>
<div id="chat-message-title">
</div>
<div id="chat-form-container">
<input id="chat-form-input" type="text" placeholder="Type a message!"/>
</div>
</div>
</body>
You should try using a combination of JQuery.
Using this, you should put an id on the input element like so:
<input type="text" id="inputField" placeholder="search"/>
Then query the input field with JQuery. Best practice would suggest to store it in a local variable as well.
let inputFieldText = $("#inputField");
Then test for the value in the text field object as returned from JQuery.
if(inputFieldText.val()){
console.log(inputFieldText.val())
}
For reference, there is also a way to do so with document.getElementById("inputField"). Just link this function to a button that runs on pressing it (such as a "submit" button). Hope this helps!