Keep textarea contents after navigating away from page? - javascript

I have a simple textarea input element:
<textarea name="comment" id="comment"></textarea>
It's on a page that a user will add items to, thus it will be navigated to and away from frequently. If a user types stuff in the textarea element and navigates away, they'll have to retype everything.
How can I make it such that whatever typed in the textarea element will store even if a user navigates away from the page? I don't want there to be a "save" button which then stores it in $_SESSION or SQL, I'm hopeful there's a method that keeps text there without also having to navigate to a new page. To clarify, sessions are A-OK, but I just don't want the user to have to press anything to store it, I'd like it automatically.

Solution
Use localStorage
window.onbeforeunload = function () {
localStorage.setItem('comment-save', document.getElementById('commment').value);
}
Then when the page is loaded
window.onload = function () {
document.getElementById('comment').value = localStorage.getItem('comment-save');
}
Explanation
window.onbeforeunload will run code before the page is closed. You can always change the event, for example
document.getElementById('comment').input
should save the value every time the user types something. The next line will store the textarea value in a localStorage item called comment-save
The code block will run when the page loads. It will locate the #comment textarea and set it's value to the saved comment.
One Last Problem
If the user submits the comment, you probably don't want to store it anymore. In your submit code, add
localStorage.removeItem('comment-save');
Why
Why use this over PHP? PHP is over-kill to save client-side data. It also wastes server-side resources.

Related

Simulate sending data to the text input field with JS

I have a task where I need to automate Sign in form authentication. For this example, I'll show you Tiktok authentication form (Mobile interface, not desktop. E-mail and password option)
If I enter text values into the fields programmatically, the Login button won't become active, and if I manually focus on the fields with a mouse click, the value disappears. These are two lines of code I run to put the value in:
let email_input = document.getElementsByName("email")[0];
email_input.value = 'sample#email.com';
I understand it needs to trigger a certain event to assign a value into it's JS model, but I can't figure out how to do it. I have tried sending change or input events onto this text field with no luck using this code:
let email_input = document.getElementsByName("email");
email_input[0].value = 'sample#email.com';
custom_event = new Event('input');
email_input[0].dispatchEvent(custom_event);
// tried also change, textInput like so:
custom_event = new Event('change');
email_input[0].dispatchEvent(custom_event);
But this does not seem to help.
So my goal is to put values into both fields Email and Password in the way it will be detected and Log in button would become active.
Any suggestion would be much appreciated
You should first focus needed input element and then execute document.execCommand with insertText command:
let email_input = document.getElementsByName("email");
email_input[0].focus();
document.execCommand('insertText', false, 'sample#email.com');
With this method input\textarea value modification should be captured by all major frameworks including Angular and Vuejs. This modification will be processed by frameworks the same way as if user pressed "Paste" option in browser main menu.
It all depends...
Who/what are you? A normal browser user? A bot? The browser author?
Because code like this is useless...
let email_input = document.getElementsByName("email")[0];
What document are you referring to? Who's document? Did you inject this instruction into the page and executed it?
You're not telling us where you're coming from, but anyway...
If you are the browser author, or you can run JavaScript macros from your browser (ie: the Classic browser) then you can do something like this...
var Z=W.contentWindow.document.querySelectorAll('input[type="password"]');
if(Z.length>0){
Z[0].value='password123';
Z=W.contentWindow.document.querySelectorAll('input[type="email"]');
if(Z.length>0){Z[0].value='email#abc.com';}
}
To automatically populate such fields, and if you also want you can SubmitButtonID.click() the submit button for as long as the isTrusted property is not tested by the website.
Continued...
Test if normal (non-custom) submit button exists and click...
Z=W.contentWindow.document.querySelectorAll('input[type="submit"]');
if(Z.length>0){
if(Z[0].hasAttribute('disabled')){Z[0].removeAttribute('disabled');} <--- Enable it if disabled
Z[0].click(); <--- automate click
}

JS: Submit or transfer input values to another HTML File?

Description:
I created this workflow: PHP loads content from a database to certain textareas. The user can edit and save content.
I created a HTML template which can be printed directly from the web browser.
So the user clicks on the "Print" button and gets a nice template which can be printed directly from the browser.
Goal:
I want jQuery or JavaScript to load / transfer the content from the input fields to another HTML document on the server, in certain div-classes.
Is this generally possible or a good idea?
Afterwards, this becomes loaded and the print dialogue of the web browser will be opened.
Present Code:
$(document).ready(function() {
$( ".print-button" ).click(function() {
$('html').load("./views/print/template-1.html");
setTimeout(function(){
window.print();
}, 1000);
})
window.onafterprint = function(e){
$(window).off('mousemove', window.onafterprint);
window.location.href = window.location.href;
};
});
So template-1.html should get the data.
First of all I think it would be a good idea to support the build in functionality of the browser. The user should be able to hit Ctrl+P or use the menu to open the print dialog.
My suggestion would be to create a <div> element that is hidden. On some event, like when the <textarea> is changed, update the <div> element with the content. Create a stylesheet for printing where the <div> element is visible and hide elements that are not for printing (like the <textarea>).
As per the description, you have mentioned that you are allowing PHP to load the data in certain text-areas and allows user to update that, so when you update this data, it'll be saving into the database for that particular text-area.
What best you can do here is keep one unique key for that shown data and when you redirect the page bind the unique key along with the page URL, so using that key on the new page where you have the template, you can get the data using select query and you can print the data wherever you want.
Afterwords on print click, the template will have the data filled in and so the user will be able to download/print the template with data, the way you wanted.
Or
If you don't want to use the PHP for getting data on the new document, you can simply pass the data object in localstorage by using below way :
var content= <your data Object>;
localStorage.setItem('print_content', content);
Now before loading the dialogue, get the data from localstorage variable and print it to div or area wherever you want. For getting data from localstorage use below way:
var printData = localStorage.getItem('print_content');
using printData var, you'll be able to get the data and using jQuery syntax you'll be able to append or display the data to div.

save and restore dynamic form value after ajax refresh

Got a page where users make comments on any desired post. Each post has a form with just one textarea field created dynamically from js and I'm wondering if anyone has an idea on how to save and restore the comment being typed by a user (i.e save whatever a user has typed so far before ajax refreshes the div holding all the post and comments and then restore back after the div refresh)
Tried creating something around this but not getting it to work:
<textarea id="comment_field" onKeyUp="return saveAndRestoreTypedStrings(this)"></textarea>
or
<textarea id="comment_field" onchange="saveAndRestoreTypedStrings(' + id + ');"></textarea>
The function:
function saveAndRestoreTypedStrings(id){
document.getElementById("post_comment").onchange = function() {
localStorage['post_comment'] = document.getElementById(id).value;
}
window.onload= function(){
if(localStorage['post_comment'])
document.getElementById(id).value = localStorage['post_comment'];
}
}
To identify the form a user is on, a unique id for that form had to be passed to the saveAndRestoreTypedStrings(id) function.
For clarity, ajax only refreshes the div holding all the posts and comments made on each post. So, that div is refreshed for latest posts and comment every 3 seconds and if a user is typing to make a comment on a post and ajax reloads the div content, the user loses whatever is being typed.
Would be pleased to get ideas around this....
window.onload fires up when the page is completly loaded soo i dont think this would apply for your case.
why dont you try using a callback function after AJAX is complete so you can "restore" the info by calling localStorage ?
Note: sorry, i cant comment yet.

jquery, replace html on submit

I have a form which is using a select list to jump around my site. This is currently using onclick window.location so user selects the page and presses go and it goes to that page.
I now need to add a small text box for the user to type in a code (say 123456) and then when they click go, it should go to the url selected, but with the [CODE] being the number entered in the box. I discovered jquery replaceAll so it gave me the idea to have this in the select html:
http ://jumptothispage.com/parts/p[CODE]/edit
http ://jumptothispage.com/jobs/j[CODE]/edit
When you press go, it would replace all [CODE] in that html with the code entered and then jump to that page selected, e.g.
http ://jumptothispage.com/parts/p123456/edit
http ://jumptothispage.com/jobs/j123456/edit
I am already using jquery on my site so makes sense to try and utilize that again. I'd appreciate a pointer and or other suggestions instead.
Thanks,
Paul.
A workaround: Store the code in a cookie, so at least it's not visible to every person who looks at the URL bar. Then in every onclick, fit it into the URL to send the user to the "right" page.
Or, have your select option's value literally read CODE, which your onclick interprets to mean "The user hasn't set the code yet." When the user types in the code, store it in a variable (in the example below, realcode), and you can then do this:
$('select#navigation option').each(function(idx, el) {
$(el).attr('value', $(el).attr('value').replace(/CODE/, realcode));
});

How do you write strings to the middle of a web page?

I'm trying to have users enter info into a form (via radio buttons), manipulate the input data, and write resulting text onto the middle of a web page--beneath the radio buttoned form. So I have variables assigned to whenever a user selects a radio button, the onClick event calling a function something like:
function saveValue1(value) {
someVariable=value;<br>
}
And when users click a Submit button, a function works like it's supposed to, ultimately writing an output string. The problem is how to write the string value in the middle of the page. I have this [pseudo]code at the end of the function (pretend the string I want to write to the page is named aVariable):
document.getElementById('aPlace').innerHTML=aVariable;
And of course there's HTML in the displayed page like this:
<div id="aPlace"></div>
After a user pressed the form's Submit button the correct output variable is displayed very briefly, and then disappears. Why is this? And how should I be writing this code instead?
Thanks for helping a newbie, as always.
The form is probably submitted. put a "return false" at the end to stop it submitting the form
It seems that the browser is refreshing? How is the form data handled?
If the form is needed only to add the text to the page, I would add a button
<button onclick="saveValue1("+value+");")>
and avoid submitting the form.

Categories