Using variables from an HTML file with an external JS file - javascript

I am using Google Scripts to make a web-app that creates a spreadsheet based on data entered on the page.
Here's some example code:
page.html
<form id="form1">
Time 1:<br>
<input type="number" id="time1" name="time1"/>
</form>
<script>
var num = document.getElementById("time1").value;
google.script.run.test(num);
</script>
Code.gs
function test(thing) {
return thing;
}
This would return undefined if I were to set an HTML element equal to the test function. How can I use the num variable from the HTML file with methods inside of my Code.gs file? I've looked through the Google APIs but there wasn't a solution that popped out at me, and I tried a couple things mentioned here on StackOverflow that didn't do the trick.
Thanks in advance.

You have to include the script in your document by linking it. Set the src attribute to the file path.

Related

How can I get a data from one html form and display it on another?

I'm using only JS and I want to get a username from one html and display it on the another html page. I'm a beginner on the programming and I have two questions:
Can I use only one JS file to do this? If yes, how?
Why it isn't working?
First page
<main>
<form action="">
<input type="text" name="login" id="login" class="login" placeholder="Login">
<a href="password.html" id='logar'>LOGAR!</a>
</form>
<span id='spanlogin'></span>
</main>
<script src="main.js"></script>
var login = document.getElementById('login').value;
localStorage.setItem("thelogin", login);
Second Page
<main>
<div>
<span id='showlogin'></span>
</div>
<div class="senha">
</div>
</main>
<script src="second.js"></script>
var ologin = localStorage.getItem('thelogin');
function showthelogin(){
document.getElementById('showlogin').innerHTML = ologin
}
window.onload = showthelogin()
Thanks for the help!
For what it's worth, the login button is just a link, it's not running the js on the first page. The js executes immediately on page load when the form is still empty. If you wrap it in a function and call the function on click, it will do what you want.
What you want, might not be what you need, but getting things to do what we want them to do can help us better understand what we need.
main.js
function savePassword(){
var login = document.getElementById('login').value;
localStorage.setItem("thelogin", login);
}
first page:
LOGAR!
In answer to your first question, you can do it with just one page. For example, read about Single-page applications.
Note that the way you're doing it is not the same thing as 'submitting' the form.
"For documents loaded from file: URLs (that is, files opened in the browser directly from the user’s local filesystem, rather than being served from a web server) the requirements for localStorage behavior are undefined and may vary among different browsers.
In all current browsers, localStorage seems to return a different object for each file: URL. In other words, each file: URL seems to have its own unique local-storage area. But there are no guarantees about that behavior, so you shouldn’t rely on it because, as mentioned above, the requirements for file: URLs remains undefined."
Its from developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

How to use function inside Javascript file using NodeJS

I start to develop a website using NodeJS and Express.
This website is about a Cinema and I have to develop a form which allows users to add a movie in database with informations like a list of actors.
I write a simple JS script to add an input to enter a new actor and I call this function addActor() in a script called dynamic.js. Here is my code :
console.log("Launching dynamic.js !")
function addActor(){
var txtNewInputBox = document.createElement('div');
txtNewInputBox.innerHTML = "<input type='text' id='newInputBox'>";
document.getElementById("actorsList").appendChild(txtNewInputBox);
}
Dynamic.js is stored in js repository so inside my app.js file I add the line :
app.use("/js", express.static("js"));
Of course I add this line in my file and I also add the button :
<script type="text/javascript" src="/js/dynamic.js"></script>
//.... some code ....//
<input type="button" name="addActor" value="ajouter" onclick="addActor()">
Here is the problem, when I click on the button, it returns "TypeError: addActor is not a function" but it prints "Launching dynamic.js !" so I don't know how to use my function addActor(). (If I called directly my function in web console it works so I don't understand)
If you have a solution, I will be glad to hear it ! Thanks ;)
Finally I find the problem. It's because I called my button "addActor" so it didn't distinguished my JS function and my HTML button.
<input type="button" name="addActor" value="ajouter" onclick="addActor()">
name="addActor" was the problem, now it works ! Thanks for helping ;)

How do I refer to a specific HTML <form> or web page from within a .js file?

I have a .js file with setCookie() and getCookie() functions which are working fine. I'm running into a problem when trying to use this same .js file with 2 different web pages. For example, one page's cookie sets name, room number, and beverage selection, while the other page's cookie sets name, address line 1, address line 2, etc...
Thus, I will need to account for differences in the 2 page's forms in the .js file. I thought that I could reference the particular form I'm addressing by its form name (they have different form names) but that isn't working:
if (document.getElementsByTagName("form") == document.getElementsByName("form1"))
{
document.cookie = 'Name = ' + userName; 'expires = ' + userExpires;
document.cookie = 'Room = ' + userPrt1; 'expires = ' + userExpires;
document.cookie = 'Drink = ' + userPrt2; 'expires = ' + userExpires;
}
Thus, my question is, when I have to add an if statement to handle code specific to one particular form (or one particular web page), how do I do this?
Thank you
EDIT: I'm not really sure this will be helpful, but since it was requested, here is the HTML:
<!doctype html>
<html lang="en">
<head>
<title>Javascript</title>
<meta charset="utf-8"/>
<link rel="stylesheet" type="text/css" href="mycss.css"/>
<script type="text/javascript" src="myjs.js"></script>
</head>
<body onLoad="javascript:getCookie();">
<header>
<img src="js.png" width="800" height="135"/>
</header>
<main>
<h2>JavaScript Cookie Test</h2>
<br><br>
<form name="form1" id="form1id" action="javascript:setCookie();">
Name: <input type="text" name="customer" id="customer" required /><br><br>
Room: <input type="text" name="roomNumber" id="roomNumber" required /><br><br><br>
What type of coffee would you like to order?<br><br> <!-- It seems radio input would be better here -->
<input type="checkbox" name="cbox" value="regular" />Regular<br>
<input type="checkbox" name="cbox" value="espresso" />Espresso<br>
<input type="checkbox" name="cbox" value="cappuccino" />Cappuccino<br>
<input type="checkbox" name="cbox" value="mocha" />Mocha<br>
<input type="checkbox" name="cbox" value="raspberry" />Raspberry<br><br>
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
</main>
As I mentioned, everything works fine in terms of setting and getting the cookie, whether my JavaScript is in the HTML file or in a separate .js file. It's only when I try to add code in the .js file that references a specific form (or web page) that I do not succeed.
Should I be referencing the web page instead of the form? If so, how would I do this in an if statement? Thank you!
EDIT: I want to add a brief clarification in case it will be helpful. What I want to know is how to reference the form or web page calling a function in the .js file. If form1 or index1.html called the setCookie() function, I want to add an if code block. If form2 or index2.html called the setCookie() function, I want to add a different if code block. Thank you.
Have you tried giving each form an id and using getElementById() instead ? I think your error is coming from the fact that getElementsByTagName returns an array so you're trying to compare an array of elements to a single element
I'm not sure to understand your question, but in case I have you could just check if the form exists, by its id.
if (document.getElementById('form1') !== null)
{
// there is a form1
}
else if (document.getElementById('form2') !== null)
{
// there is a form2
}
for the first, getElementsByName() doesn't return single node, but a node collection, so if you want to access the first matching node, you have to use
document.getElementsByName("form1")[0]
For the second, you can simply use document.forms property where you have access to all forms on your page.
EDIT:
In document.forms you can access to form by index of its occurrence (document.forms[1] returns the second form on page) or you can use name attribute value (document.forms["form1"] returns form with name "form1").
Okay, I finally figured out an answer to this.
HTML:
<script type="text/javascript">var formName = "form1"</script>
<form name="form1" action="javascript:setCookie(formName);">
insert form code...
</form>
Then, in the .js file:
function setCookie(formName)
{
insert cookie code...
}
And the form name is passed to the JavaScript page, so I can use it to add cookie code that is specific to form1.
I was hoping to find a way to know which form called the JavaScript page, but I'm starting to think that's not possible, since the question has been posted for 5 days without a resolution. Fortunately, this resolves the issue just as easily as knowing which form called the JavaScript page.
I appreciate everyone's input.

Javascript: Get the value of attributes of "FORM " which is created in .html to external .js file

I have written the small html code where javascript/jquery is inserted inside the tag. This approach works fine.
Now I want to divide this single file into ".html" & ".js". Where I want to separate all javascript/jquery coding part into ".js"
But the problem here I faced is that I am not able to read the values(in ".js") of any field which I have created in ".html"
Example
test.html:
<form name="attachlaunchform" id="attachlaunchform" class="form">
<input type="text" name="serial_number" id="serial_number" maxlength="16">
test.js:
serial_num=document.attachlaunchform.serial_number.value
I have included source of my external js file also.
But if I put all these in single file in test.html, it works.My query is how can I get the text box or any other value in .js?
Lets say-
Assuming you have number of events in your html file like-
$('element1').click(function(){});
$('element2').keydown(function(){});
$('element1').bind('click mouseover',function(){});
function initFunction(){
//something
}
$(document).ready(function(){
initFunction();
});
You can separate it by making an external .js file(you already trying this)
Standardize this file as an extension not just an external source.
Now separating all above functions in .js file-
(function($){
function events(){
$('element1').click(function(){});
$('element2').keydown(function(){});
$('element1').bind('click mouseover',function(){});
}
function initFunction(){
//something
}
$(window).on('load',function(){
events();
initFunction();
});
});
and then simply use this file in your html file.

Wordpress, PHP, Javascript, how to get variable within a js function?

Purpose: passing html hidden input variable into javascript function.
Working on a wordpress plugin and got stuck with javascript.
Here's hidden input I am trying to get, which is variable_product_id. This gets set when an user selects an dropdown options dynamically.
<form class="hello">
<input type="hidden" name="variation_id" value="">
</form>
Outside of form class hello, there's plugin function in below, and I am trying to get and set "variation_id" right after product_id within "wp.CheckoutButton.apply".
if( !is_user_logged_in() )
{
echo "<script type=\"text/javascript\" >
var temp = document.getElementsByName('variation_id');
//<![CDATA[
wp.CheckoutButton.apply({
BUY_BUTTON_LINK_URL:\"www.website.com/?p=42&product_id=\"+temp,
\"\":\"\" });
//]]>
</script>";
}
"wp.CheckoutButton.apply" prints button on the screen which will pass product_id that I am passing.
It's been working with no variable product options within woocommerce, for variable product, I have to get the selected hidden variation_id when an users changes values(dropdown input).
Can I use document.getElementsByName('variation_id');?
If so, how can I pass 'variation_id' within "wp.CheckoutButton.apply" function?
Is "+temp" within apply function legal?
A possible duplicate of this :
php variable into javascript
Sometimes, some data is needed in js files / js code like the base url of the site. In this case, it is best practice to create a JS variable within the header html tag. In your header tags, create a variable like below :
<script>
var baseUrl = <?php echo get_site_url(); //if get_site_url echos the result itself, then no need to use echo ?>
</script>
Now, in all of your JS files and inline js code you will have this variable and you can use it. Simply it is a global js variable (i just made it up, dont know if js has :P )
Now you can use that variable every where in your js files and js codes.
Notge : Please create baseUrl variable at top most of the header tag or some where, so that no js file is included before it.
**Edit : **
Now to get variation_id from your form element, add id to your element as below:
<input type="text" name="variation_id" id="variation_id" value="" />
In js using jquery :
var variation_id = $("#variation_id").val();
and in wp.CheckoutButton.apply , instead of temp, use variation_id. It is correct i think, but try it.
Hope this will help.
For that you need to create a localize script that can help to call a site url in js file or js function.
http://codex.wordpress.org/Function_Reference/wp_localize_script

Categories

Resources