use variable from js file into another js file - javascript

I am doing an autofill extension for chrome. I made the html file where user put his information and i want that these information will be saved, because i need to use that information as a variable from a js file.
This is the html popup:
<html>
<head></head>
<body>
<div class="simple-form">
<form method="post">
<input type="text" name="fname" id="full_name" placeholder="Write here your full name"><br><br>
<input type="email" name="email" id="email" placeholder="Write here your email"><br><br>
<input id="save" type="button" value="Salva">
</form>
</div>
<script type="text/javascript" src="scriptExport.js"></script>
</body>
</html>
and this is the js file:
const button = document.getElementById('save');
button.addEventListener('click', updateButton);
function updateButton() {
if (button.value === 'Save') {
button.value = 'Done';
var full_name_E = document.getElementById('full_name').value;
var email_E = document.getElementById('email').value;
}
else {
button.value = 'Save';
}
}
I need to load full_name_E and email_E in another js file that is the autofiller.
I tried with import and export but it doesn't work.

Your problem is, that full_name_E and email_E are only available in the local scope of the function updateButton. To make the available at the global scope, initialize them at the top of your code:
const button = document.getElementById('save');
var full_name_E;
var email_E;
button.addEventListener('click', updateButton);
function updateButton() {
if (button.value === 'Save') {
button.value = 'Done';
full_name_E = document.getElementById('full_name').value;
email_E = document.getElementById('email').value;
}
else {
button.value = 'Save';
}
}
If you want to learn more about this topic:
https://developer.mozilla.org/en-US/docs/Glossary/Scope
https://scotch.io/tutorials/understanding-scope-in-javascript

Also you can pass these variable in a function which you can define in your other js file.

Related

How do I update this form field so it stays hidden on page load?

I have this form in my Django project. On page load it should only show the entity name, but it's showing both the entity-name and quote-text fields.
The page should only show the quote-text field when the entity-name is not in the database.
The toggle works for all cases except page load. It's the line if (entities.length === 0) I need to update but I'm not sure what to update it to.
<form>
<label for="entity-name">Entity Name:</label>
<input type="text" id="entity-name" name="entity-name" onkeyup="searchEntities()">
<div id="search_results"></div>
</form>
<form id="quote-form">
<label for="quote-text">Quote Text:</label>
<textarea class="form-control" id="quote-text" name="quote-text" rows="3"></textarea>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<script>
function searchEntities() {
const entityName = document.querySelector('#entity-name').value;
console.log('hi');
console.log(entityName);
fetch(`/search-entities/?entity_name=${entityName}`)
.then(response => response.json())
.then(entities => {
const searchResults = document.querySelector('#search_results');
searchResults.innerHTML = '';
if (entities.length === 0) {
// Show the quote field
document.querySelector('#quote-form').style.display = 'block';
} else {
entities.forEach(entity => {
const p = document.createElement('p');
p.innerHTML = entity.name;
searchResults.appendChild(p);
});
// Show the quote field
document.querySelector('#quote-form').style.display = 'none';
}
});
}
</script>
Try this and see if it works, this will run your script after the page is loaded and ensures the whole DOM is loaded first and then execute the script:
<script>
....
window.onload = function() {
searchEntities();
};
</script>

Check the answer

I try to see if the word entered in the form is the correct one. If it is correct then I open another page and otherwise I will get an error message, but I don't know how to make the script for this. Also I don't want to use a submit button.
<form id="form">
<input type="text" name="inputBox" placeholder="Enter your answer"><br>
</form>
Try this:
In this code I check with the key event, if I press enter I call and ask if the answer is "Hello" is correct and I open another page, otherwise I send an alert with an error
<form id="form">
<input id="MyEnter" type="text" name="inputBox" placeholder="Enter your answer"><br>
</form>
<script>
var myenter = document.getElementById("MyEnter");
myenter.addEventListener("keypress", function(event) {
if (event.key === "Enter") {
event.preventDefault();
var answer = 'Hello'
var mytext = document.getElementById("MyEnter").value;
if (mytext==answer) {
alert('opening another page');
window.open("https://www.google.com");
}else{
alert("Incorrect answer");
}
}
});
</script>
const input = document.querySelector('input');
const error = document.querySelector('p.error');
const woohoo = document.querySelector('p.woohoo');
const correctAnswer = 'foo bar baz';
const handleInput = (condition) => {
if (condition) {
error.style.display = 'block';
woohoo.style.display = 'none';
return;
}
error.style.display = 'none';
woohoo.style.display = 'block';
window.open('https://google.com');
};
input.addEventListener('keyup', () => handleInput(input.value !== correctAnswer));
<form id="form">
<input type="text" name="inputBox" placeholder="Enter your answer" />
<p class="error" style="color: red; display: none">Incorrect</p>
<p class="woohoo" style="color: green; display: none">Correct</p>
</form>

Google App Script setTimeout Function problem

I have a typical Google App Html form that records the data entered in a spreasheet.
Here are the files.
HTML Form:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include("css");?>
</head>
<body>
<h2>Feedback Form</h2>
<div id="message"></div>
<!--- BUTTON New registration --->
<br /><input id="button-responder" type ="button" value = "New registration"
onclick="submitResponder('button-responder'),
submitTransition('message');" style="display:none;" />
<!--- FORM --->
<form id="my-form">
<br /><input id="name" type="text" name="name" placeholder="Your Name">
<br /><input id="email" type="email" name="email" placeholder="Your Email">
<br /><textarea id="comment" rows="10" cols="40" name="comment"></textarea>
<!--- BUTTON submitForm --->
<br /><input id="btn" type="button" value="Submit"
onclick="submitForm(this.parentNode),
document.getElementById('my-form').style.display='none',
submitResponder('button-responder'),submitTransition('message');" />
</form>
<?!= include("test-js");?>
</body>
</html>
Google Script:
function doGet(request) {
return HtmlService.createTemplateFromFile('index')
.evaluate();//not all caps but it has to match the name of the file and it doesn't - Change to PAGE
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
function submitData(form) {
var subject='New Feedback';
var body=Utilities.formatString('name: %s <br />Email: %s<br />Comment: %s', form.name,form.email,form.comment);
var folderId = "my-folder-ID"; // Please set the folder ID. // Added
var blob = Utilities.newBlob(body, MimeType.HTML, form.name).getAs(MimeType.PDF); // Added
var file = DriveApp.getFolderById(folderId).createFile(blob); // Added
return Utilities.formatString('name: %s <br />Email: %s<br />Comment: %s<br />
PDF: <a target="_blank" href="%s">see your PDF file</a>',
form.name,form.email,form.comment,file.getUrl());
function userClicked(userInfo){
var url = "https://docs.google.com/spreadsheets/d/my-spreadsheet-ID";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Data");
ws.appendRow([userInfo.name, userInfo.email, userInfo.comment]);
}
test-js
<script>
function submitForm(form) {
google.script.run
.withSuccessHandler(function(value){
document.getElementById('message').innerHTML = value;
document.getElementById('name').value = '';
document.getElementById('email').value = '';
document.getElementById('comment').value = '';
})
.submitData(form);
}
function submitResponder() {
var x = document.getElementById("button-responder");
var xx = document.getElementById("my-form");
var xxx = document.getElementById("message");
if (x.style.display === "none") {
x.style.display = "block";
xx.style.display = "none";
xxx.style.display = "block";
} else {
x.style.display = "none";
xx.style.display = "block";
xxx.style.display = "none";
}
}
function submitTransition() {
setTimeout(function() {
document.getElementById('message').style.color = 'blue';}, 2500);
}
document.getElementById("btn").addEventListener("click",doStuff);
function doStuff(){
var userInfo = {}
userInfo.name = document.getElementById("name").value;
userInfo.email = document.getElementById("email").value;
userInfo.comment = document.getElementById("comment").value;
google.script.run.userClicked(userInfo);
document.getElementById("name").value= "";
document.getElementById("email").value= "";
document.getElementById("comment").value= "";
}
</script>
css:
<style>
#message {
color: transparent;
}
</style>
QUESTION
Now in Google Script file function
function submitData (form)
and in test-js file function
function doStuff ()
they do their job well but with a latency of around 2.5s
then for Google Script to file the function
return Utilities.formatString
can show the result (name - email - comment - PDF Url)
its conclusion must be awaited, 2.5s.
Functions in variables.
In test-js file function
function submitResponder ()
makes the fields linked to the ID (message) visible with variables
name: example-name
email: example-email
comment: example-comment
PDF: see your example-PDF file
and the field linked to the ID (button-responder)
"New registration" button
Then upon loading the index.html page
the form and the "submit" button are shown,
edit the fields by clicking on submit
the form is hidden, the "New registration" button appears
and after about 2.5s the edited fields (name-email ....) also appear.
Click on the button "New registration" below
the form reappears as at the beginning, clearly not with a reload page, but simply with
display = "none"
display = "block"
Now here's the problem I can't solve:
By re-editing the fields and clicking again on submit-form
the fields edited the previous time appear again immediately
name: example-name
email: example-email
comment: example-comment
PDF: see your example-PDF file
and after about 2.5s they update with the new edited fields
name: new-name
email: new-email
comment: new-comment
PDF: see your new-PDF file
Now with the function
function submitTransition () {
setTimeout (function () {
document.getElementById ('message'). style.color = 'blue';}, 2500); }
and with style
#message { color: transparent; }
I'm trying to find a solution to delay (hide) the display of the old fields until the new ones are updated.
It is certainly not the right way.
I hope I have been clear in the explanation, your help will be very much able.
Thanks in advance.
You want to show the texts and button of "New registration" after "submit" button was clicked and the script of submitData was finished.
If my understanding is correct, how about this modification?
The reason of your issue is that google.script.run is run with the asynchronous process. By this, before the script of submitData is finished, document.getElementById('my-form').style.display='none', submitResponder('button-responder') and submitTransition('message') are run.
Modified script:
Please modify your script as follows.
From:
<br /><input id="btn" type="button" value="Submit"
onclick="submitForm(this.parentNode),
document.getElementById('my-form').style.display='none',
submitResponder('button-responder'),submitTransition('message');" />
To:
<br /><input id="btn" type="button" value="Submit" onclick="submitForm(this.parentNode)" />
And
From:
function submitForm(form) {
google.script.run
.withSuccessHandler(function(value){
document.getElementById('message').innerHTML = value;
document.getElementById('name').value = '';
document.getElementById('email').value = '';
document.getElementById('comment').value = '';
})
.submitData(form);
}
To:
function submitForm(form) {
google.script.run
.withSuccessHandler(function(value){
document.getElementById('message').innerHTML = value;
document.getElementById('name').value = '';
document.getElementById('email').value = '';
document.getElementById('comment').value = '';
document.getElementById('my-form').style.display='none'; // Added
submitResponder('button-responder'); // Added
submitTransition('message'); // Added
})
.submitData(form);
}
And, by above modification, you can also remove setTimeout as follows.
From:
function submitTransition() {
setTimeout(function() {
document.getElementById('message').style.color = 'blue';}, 2500);
}
To:
function submitTransition() {
document.getElementById('message').style.color = 'blue';
}
Reference
Class google.script.run (Client-side API)
google.script.run is an asynchronous client-side JavaScript API available in HTML-service pages that can call server-side Apps Script functions.
If I misunderstood your question and this was not the result you want, I apologize.

How to get the value of a checkbox using getelementbyID inside a form

I have a code which worked fine while I was testing it now I decided it to include it inside a form and it just does not want to work. If I remove the form tag it works and with the form tag it does not.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<script>
function action() {
var checkBox = document.getElementById("UPCheck");
if (checkBox.checked == true){
window.localStorage['username'] = document.getElementById('username').value;
window.localStorage['password'] = document.getElementById('password').value;
window.localStorage['unpwchecked'] = "yes";
alert("Saved!");
}
else
{
window.localStorage['username'] = "";
window.localStorage['password'] = "";
window.localStorage['unpwchecked'] = "";
}
}
function action2() {
document.getElementById('username').value = window.localStorage['username'];
document.getElementById('password').value = window.localStorage['password'];
}
</script>
</head>
<body>
<form>
<input type="text" id="username" name="username" value="">
<input type="text" id="password" name="password" value="">
Save username / password in cookies: <input type="checkbox" id="UPCheck" name="savelocalunpw">
<p><button onclick="action()" type="button">Save values!</button></p>
<p><button onclick="action2()" type="button">Load values!</button></p>
</form>
<script>
var alerted = localStorage.getItem('unpwchecked');
if (alerted == 'yes') {
document.getElementById('username').value = window.localStorage['username'];
document.getElementById('password').value = window.localStorage['password'];
document.getElementById("UPCheck").checked = true;
}
</script>
</body>
</html>
Remove the form tag and values are properly saved in localstorage.
The problem comes from the function name. If you rename
function action()
to
function action1()
and also modify
<button onclick="action1()" type="button">Save values!</button>
then your code will work.
I notices that without the form tag, the code works ok. If you add the form element, then you will get a console error, stating that action() is not a function. I'm just guessing that there is a conflict between the function name action() and the form attribute action
Try:
var isChecked = document.getElementById("UPCheck").checked;
Probably better practice to add an event handler for the buttons, that works with the form tags. Kind of interesting that it works with renaming the function.
JS
document.getElementById("save").addEventListener("click", function(){
var checkBox = document.getElementById("UPCheck");
if (checkBox.checked == true){
window.localStorage.username = document.getElementById('username').value;
window.localStorage.password = document.getElementById('password').value;
window.localStorage.unpwchecked = "yes";
alert("Saved!");
}
else
{
window.localStorage.username = "";
window.localStorage.password = "";
window.localStorage.unpwchecked = "";
}
});
document.getElementById("load").addEventListener("click", function(){
document.getElementById('username').value = window.localStorage.username;
document.getElementById('password').value = window.localStorage.password;
});
var alerted = localStorage.getItem('unpwchecked');
if (alerted == 'yes') {
document.getElementById('username').value = window.localStorage.username;
document.getElementById('password').value = window.localStorage.password;
document.getElementById("UPCheck").checked = true;
}
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<form>
<input type="text" id="username" name="username" value="">
<input type="text" id="password" name="password" value="">
Save username / password in cookies: <input type="checkbox" id="UPCheck" name="savelocalunpw">
<p><button id = "save" type="button">Save values!</button></p>
<p><button id = "load" type="button">Load values!</button></p>
</form>
</body>
</html>
You can use "dot" notation for localStorage.

Displaying saved localstorage variables in a textfield - javascript

i got some saved variables using localstorage, what i want to do is to put them into textfields automatically each time the page loads
<script language="javascript">
function save() {
var value1 = document.getElementById("email").value;
var value2 = document.getElementById("password").value;
localStorage.setItem("eaddress", value1);
localStorage.setItem("pwd", value2);
}
</script>
i've got some textfields on the page namely email and password
If you want to do this with jQuery, this should accomplish what you're trying to do. Please note that I couldn't get the demo running in the snippet below because Stack Overflow is preventing form submissions.
$(function() {
var
$email = $('#email'),
$password = $('#password'),
emailValue = localStorage.getItem("eaddress"),
passwordValue = localStorage.getItem("pwd");
// SAVE VARIABLES TO LOCAL STORAGE
$('form').on('submit', function() {
localStorage.setItem("eaddress", $email.val());
localStorage.setItem("pwd", $password.val());
});
// IF EMAIL AND PASSWORD ARE SAVED, PREPOPULATE THE FORM FIELDS
if (emailValue != null) {
$email.val(emailValue);
}
if (passwordValue != null) {
$password.val(passwordValue);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="email" id="email" />
<input type="password" id="password" />
<button type="submit">Submit</button>
</form>

Categories

Resources