As the title states, I have an issue where my HTML file is not finding a function in a javascript file, even though the javascript file is added and loaded in the <head>.
The code in the HTML file
In <head>:
<script type="text/javascript" src="javascripts/num.js"></script>
In the <body>:
<input type="text" id="firstName" placeholder="firstName"></input>
<input type="text" id="lastName" placeholder="lastName"></input>
<script>
function start() {
readNames();
}
</script>
<input class="btn btn-github" type="submit" value="Submit" onclick="start();" id="calculate"></input>
In num.js:
function readNames() {
firstName = document.getElementById("firstName").value;
alert(firstName);
lastName = document.getElementById("lastName").value;
alert(lastName);
}
The first problem I see is that you're not enclosing your javascript function definition with like this:
<script>
function readNames() {
firstName = document.getElementById("firstName").value;
alert(firstName);
lastName = document.getElementById("lastName").value;
alert(lastName);
}
</script>
From the code I see, I would take out the start(); function as it just calls readNames(). In your onclick event, call readNames();
If you continue to have problems, try inserting "event" in the function definition, like this: readNames(event);, and when you call it: onclick="readNames(event)".
Firebug can help solve problems with javascript, with Firebug. To use it, download the extension in either Firefox or Chrome (I prefer Firefox), and hit F12. When you enter something in the textboxes and click submit, does it give you any error messages?
Why not simply call the click event within the JS file :
function readNames() {
firstName = document.getElementById("firstName").value;
alert(firstName);
lastName = document.getElementById("lastName").value;
alert(lastName);
}
document.getElementById("calculate").onclick=function(){readNames()};
and remove the onclick attribute :)
Related
I've created a pop-up email dialog box within google's html editor as follows with the input for email as follows:
<input type="email" name="email" class="form-control" id="mail" aria-describedby="emailHelp" value="">
In my .gs file I'm storing the value of my cell containing the email address I want to use as follows:
function getEmail()
{
var s=SpreadsheetApp.getActive().getSheetByName("Template");
var row=15;
var column=3;
var contactAddress=Utilities.formatString('%s',s.getRange(row, column).getValue());
Logger.log(contactAddress);
}
This works fine and is capturing the email address correctly and logging it. I now need to change the 'value' of my email input so that it populates with this address when the diolog opens. So I have the following in my HTML file:
window.onload = function (contactAddress)
{
document.getElementById('mail').value=contactAddress;
}
However, this is resulting in '[object Event]' being populated. I feel I'm close here but can't quite get it over the line!!!!
UPDATE:
So I added this to my .gs:
function showDialog() {
var html = HtmlService.createHtmlOutputFromFile('emailTemplate')
.setWidth(800)
.setHeight(500);
html.myvar = new getEmail();
html.evaluate().getContent();
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.showModalDialog(html, ' ');
}
However, when I run the script I get an error stating Object does not allow properties to be added or changed.
Edit: Original answer deleted.
So here is my answer to your problem. Tested it out, and it works.
My HTML page is set up like this just to test it:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function onSuccess(contact) {
//var contactAddress = google.script.run.getEmail();
document.getElementById('mail').value=contact;
}
google.script.run.withSuccessHandler(onSuccess).getEmail();
</script>
</head>
<body>
<input type="email" name="email" class="form-control" id="mail" aria-describedby="emailHelp" value="">
</body>
</html>
My .gs file contains
function getEmail()
{
var s=SpreadsheetApp.getActive().getSheetByName("Sheet1");
var row=1;
var column=3;
var contactAddress=Utilities.formatString('%s',s.getRange(row, column).getValue());
Logger.log(contactAddress);
return contactAddress;
}
The only real difference is that I added a return statement (and changed the row from 15 to 1 for my test).
Seems the main problem was how you were calling the function on the HTML page. It needed a google.script.run.withSuccessHandler() call instead of a window.onload = function() call.
I have tried to call the function using window.onload but it works only when I place it body tag as below but when I place it in the head tag (commented out) it doesn't work though the function gets called (I have put an alert and checked.)
<!DOCTYPE html5>
<html>
<head>
<script>
function onl()
{
var x=document.forms[0].elements[0].name;
document.write(x);
}
//window.onload = onl();
</script>
</head>
<body>
<form name=usern>
<input type = "text" name ="username">
<input type = "password" name ="password">
<input type ="submit" name="sybmitb">
</form>
<script>
window.onload = onl();
</script>
<div id = "txt">
</div>
</body>
</html>
It doesn't run in the head because the brackets used after the assignment cause the function to immediately be run. That mean it causes an error because the document hasn't loaded yet and so causes the form elements to be undefined.
In the head, if you change
window.onload = onl();
to
window.onload = onl;
Then it will work.
You must pass the handler function to document.load (or window.load), not the return of your function. So use document.onload = onl; instead of document.onload = onl(); (see more here : https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload)
So in result :
<!DOCTYPE html5>
<html>
<head>
<script>
function onl()
{
var x=document.forms[0].elements[0].name;
document.write(x);
}
document.onload = onl;
</script>
</head>
<body>
<form name=usern>
<input type = "text" name ="username">
<input type = "password" name ="password">
<input type ="submit" name="sybmitb">
</form>
<div id = "txt">
</div>
</body>
</html>
Regards,
Julien Q.
Edit : Sorry I misread before ;)
When you assign a function like that, you need to be sure not to invoke it. When you put parentheses on the end of a function name, it will be invoked immediately even if it's being assigned to something like the window's load event.
So, you simply have to replace onl() with onl:
window.onload = onl;
As for why it works in the body, it's because the document has pretty much finished loading when it gets to the end of the body.
Assigning onl() to the window's onload property isn't erroneous because you're assigning the return value of onl(), which is undefined, to window.onload.
Also, I'd recommend not using window.onload but document.onload, because document.onload is fired when the DOM is ready, not when the files requested are ready.
I have a login.js which has a function which is called when the clickme button in the HTML is pressed.
document.getElementById('clickMe').addEventListener('click',execuateAllCode);
The line below is in the function that is called by the clickme button and it does not work
var password = document.getElementById("password").value;
It gives this error:
Uncaught TypeError: Cannot read property 'value' of null
popup.html contains this code:
...
<input id="clickMe" type="button" value="clickMe"/>
<input type="password" name="password" id="password" value="temppassword" placeholder="Password"/>
...
The error should mean that there is no element that contains an id="password". But I do have something with that id. Can the function in login.js not "see" the input in the HTML file?
EDIT 1:
I have tried to add:
window.onload = function() {
execuateAllCode()
};
To the .js file, but this does not get rid of the error, it also causes errors in other parts of the code and stops the styling.
The HTML:
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<input id="clickMe" type="button" value="clickme"/>
<script language="javascript" src="login.js"></script>
<input type="text" name="email" id="username" value="user#email.com" placeholder="Email"/>
<input type="password" name="password" id="password" value="temppass" placeholder="Password"/>
</body>
</html>
login.js:
document.getElementById('clickMe').addEventListener('click',execuateAllCode);
function execuateAllCode() {
document.write("<br />" + "From login" + "<br />");
var output;
output = FunctionOne();
document.write("<br /> the output: " + output + "<br />");
}
function FunctionOne(){
...
var password = document.getElementById("password").value;
var user_name = document.getElementById("username").value;
...
}
Your are fetching that element which not loaded yet(DOM is not loaded). That's why you are facing the issue.
window.onload = function() {
/*Do that stuff in this function*/
};
For more reference check this link.
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload
Hope this will help :)
Your popup.html is not the page that includes login.js - that's why code in login.js does not find a DOM element with id="password". The page that includes login.js contains, however, a button with id="clickMe".
After seeing your execuateAllCode:
http://www.w3schools.com/jsref/met_doc_write.asp - "The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML." Add a div element where you put any output using innerText or innerHTML instead of using document.write.
What you need to do is :
Initialize variable password outside the function and then declare it
Or you can use window.onload = function_Name;
Why don't you call function on login button click or any event ?
A great way to debug javascript is warping your variables and events in a console.log and checking their result in the browser console.
Try adding console.log(password) right after you set it equal to the value of the input. This will tell you if that jQuery functionality is working. That will help you find out what the HTML is "seeing"
im trying to change the innerhtml of an element but it keeps reseting back to "ddd" on every click of the button
<form>
<p id="passError">ddd</p>
<button id="submit">Login</button>
</form>
<script type="text/javascript">
document.getElementById("submit").onclick = function(){changeit()};
function changeit()
{
pError = document.getElementById("passError");
pError.innerHTML = ("wrong password");
</script>
First you are missing the } on the function and then with the submit you are submitting the form which you have to prevent. You don't need a wrapper function for the changeit function you may pass it directly to the onclick variable.
<form>
<p id="passError">ddd</p>
<button id="submit">Login</button>
</form>
<script type="text/javascript">
document.getElementById("submit").onclick = changeit;
function changeit(event)
{
event.preventDefault();
pError = document.getElementById("passError");
pError.innerHTML = "wrong password";
}
</script>
You forgot one thing and have another typo mistake:
you forgot the closing curly bracket } at the end of your function changeit() as mentionned by #antyrat;
you want to put directly the string in the innerHTML assignation, not using parenthesis. (see the innerHTML documentation from MDN)
Moreover, you can also pass directly your changeit function instead of using an anonymous function and put your pError in a proper declarated variable. :)
As you are using a <form>, you also need to prevent the default behavior of the submit button by calling the preventDefault() function on the click event in your function.
The following code is working. I corrected these elements and just add some indentation and spacing to have a code more user-friendly.
<form>
<p id="passError">ddd</p>
<button id="submit">Login</button>
</form>
<script type="text/javascript">
document.getElementById("submit").onclick = changeit;
function changeit(evt) {
evt.preventDefault();
var pError = document.getElementById("passError");
pError.innerHTML = "wrong password";
}
</script>
I'm stuck on what seems like a trivial issue and I'm probably gonna kick myself for missing this..Anyway, my issue is I'm failing to get the value from a text field.
HTML:
<form>
<label for="">Enter Username:</label>
<input id="usernameText" type="text" size="30" />
<input type="button" value="Generate" onclick="generateQuery(); return false;" />
</form>
Javascript:
<script type="text/javascript">
var username = $("#usernameText").val();
function generateQuery(){
alert(username);
}
</script>
I did the following if (jQuery) {.. and made sure JQuery is loaded.
In the alert it displays an empty dialog box.
If I included the $(document).ready(); into my script the function generateQuery does not get called. Any idea why..?
<script type="text/javascript">
$(document).ready(function(){
var username = $("#usernameText").val();
function generateQuery(){
alert(username);
}
});
</script>
Assign your variable within the function.
function generateQuery(){
var username = $("#usernameText").val();
alert(username);
}
As for your other question, "If I included the $(document).ready(); into my script the function generate does not get called. Any idea why..?"
This happens because of scope. You wrap generateQuery inside an anonymous function when you add a document.ready handler, and therefore it's not visible to your button onclick="generateQuery()" code.
Here it will call while the page is loading.So whenever the page is loading the text box is empty.Try to write within a function.
function generateQuery(){
var username = $("#usernameText").val();
alert(username);
}
When you write in document.ready it will cal;l while the page is loading.If you need the value of username then call explicitly.
The value is being derived the first time through. So when the page is first loaded.
<script type="text/javascript">
function generateQuery(){
var username = $("#usernameText").val();
alert(username);
}
</script>
Here you are defining the function you have to call the function in order to get it run use this generateQuery(); line to call your function.
where are you calling the function????
i think you need:
<script type="text/javascript">
$(document).ready(function(){
generateQuery();
});
function generateQuery(){
var username = $("#usernameText").val();
alert(username);
}
</script>