gs function passing 'undefined' to jsfunction (Dynamic Form Update) - javascript

I'm having a problem with a dynamically updated form in Google Apps Script. The form is in an HTML template (say index.html) as follows:
<form id="login">
<p>Enter username and password below, or use the links to the right for more services:</p>
<input type="text" placeholder="username" id="username" name="username" />
<input type="password" placeholder="password" id="password" name="password"/>
<input type="button" value="Login" onclick="google.script.run.withSuccessHandler(form_login).processForm(this.parentNode)" id="login_button" />
</form>
There is also a div designated for the output:
<div id="output">test value</div>
And a javascript function to update said div:
function form_login(msg) {
var div = document.getElementById('output');
div.innerHTML = div.innerHTML+msg;
}
The function within the gs file that deals with this is as follows:
function form_login(formObject) {
//connect to users spread sheet
var userssheet = SpreadsheetApp.openById("SPREADSHEET-ID-STRING");
//get variables handed over and existing on page
var username = formObject.username;
var pass = formObject.password;
//get where data range in spreadsheet
var searchrange = userssheet.getActiveSheet().getDataRange();
//check if username exists and return password (change to check if password and username are correct and)
if (find(username, searchrange)) {
var enteredpassword = searchrange.getCell(find(username, searchrange),4).getValue();
var message = (username+" Found! Password is "+enteredpassword); //get password value
} else {
var message = (username+" Not Found!");
}
//check if password entered is correct
if (enteredpassword) {
if (enteredpassword==pass) {
message = message + "Correct Password";
} else {
message = message + "Incorrect Password";
}
}
return message;
}
(Obviously I'm still building the functionality).
The problem, which will probably turn out to be an obvious oversight on my part, is with the gs function. Whatever it returns is outputted as 'undefined' into the HTML. Even when i change return message; in the function to something like return "hello";, I still get undefined appended to the output div (I tried using toString(); in the javascript function, but that didn't change anything).
Any ideas? What am I missing?

Found out what the problem was, and as I assumed, it was a mistake on my side. The button action (which I copied then edited from developers.google.com/apps-script/guides/html/communication#forms was:
onclick="google.script.run
.withSuccessHandler(form_login)
.processForm(this.parentNode)"
The problem was that I forgot to change processForm to the new gs function name: form_login. I changed it (to do_form_login, and changed the function name in the code to avoid confusion with the javascript code), and it worked like a charm (:
Note: Thanks Sandy for the help, you made me scrutinize the code and find out this mistake.

Related

How do I display an error message if the input is wrong on HTML

Im trying to display an error message in RED beside the input field to let the user know, however I dont know why my error message is not working. The requirement for the input is starting with a capital letter, followed by non special characters (any alphabets) please help me see what is wrong with my code
I am still new to HTML and I know many people said about regex but im not sure i have not learn that
<html>
<script>
function validateForm() {
var fname = document.getElementById("fname").value;
if (/^[A-Z]\D{2,30}$/.test(fname) == false)
{
document.getElementById("errorName").innerHTML = "Your email must be filled";
return false;
{
return name;
}
</script>
<style>
#errorName
{
color:red;
}
</style>
<form action="handleServer.php" method="get" onSubmit="return validateForm()">
<body>
<!-- starting with first name-->
First name: </br>
<input id="fname" type="text" name="fname" size="30">
<span id="errorName"></br>
<input type="submit" value="Submit">
</body>
</form>
</html>
I see your if statements are not closed properly and also the input box.
Please find codepan
function validateForm() {
console.log(1);
var fname = document.getElementById("fname").value;
if (/^[A-Z]\D{2,30}$/.test(fname) == false)
{
document.getElementById("errorName").innerHTML = "Your email must be filled";
return false;
{
return name;
}
}
}
When i tend to use regex i store it in its own value like this:
const patternName = /[0-9]|[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/|#]/;
let resultName = patternName.test(name.value);
The code above checks if the name contains anything from the regex above and if it does resultName will return true.
Next we can do the following:
If name is empty you get an error and it contains anything from the regex above we. In this case we show the error
If resultName is true we know that name contains something from the regex, so that it's not a valid name.
If not we show success message
if (name.value === "" || resultName) {
showErrorName();
} else {
showSuccessName();
}`

Beginning Javascript form validation

this is my first time posting.
I'm in a beginner Javascript class with the following assignment:
"Students are required to enter into a text box their course information in the following format:
AAA.111#2222_aa-1234
Your Web page will ask the user to type their information in a text box. The user will then click a form button named validate. If the format is correct a message will be generated below the button that reads "Correct Format". If the format is incorrect a message will be generated that reads "Incorrect Format". "
After my first attempt, I got the following feedback:
"You do not need a form for this assignment .You only need a text box and a button. Place your function on your button (onClick event). You only need one function for this assignment.  Your function should include getting the users input from the text box. You can use getElementById() and .value it should also include the regular expression, and what to so if it is correct or wrong."
So far I have the following:
function isValid(text) {
var myRegExp = /([A-Z]{3})\.\d{3}#\d{4}_(sp|su|fa)-\d{4}/;
return (myRegExp.test(text);
if (isValid(document.getElementById("course".value) {
document.getElementById("output").innerHTML = "Correct Format";
} else {
document.getElementById("output").innerHTML = "Incorrect Format"
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 6 Assignment</title>
</head>
<body>
<p>Please enter your course information in the following format AAA.111#2222_aa-1234:</p>
<input type ="text" name ="course" id="course" />
<button onclick="isValid()">Validate</button>
<p id="output"></p>
<script src = "registerFourth.js"></script>
</body>
</html>
So sorry if I am not posting this correctly. My code is telling me I have a "Parsing Error: Unexpected Token" and when I fill in the text box and click Validate nothing happens. Thank you!
There are multiple issues in your approach.
1. Your isValid method expects text parameter which is not required
2. Your isValid method is recursive, I don't see why that is needed.
Please check below if it works for you.
function isValid() {
var myRegExp = /([A-Z]{3})\.\d{3}#\d{4}_(sp|su|fa)-\d{4}/;
var text = document.getElementById("course").value;
var match = myRegExp.test(text);
if(match) {
document.getElementById("output").innerHTML = "Correct Format";
} else {
document.getElementById("output").innerHTML = "Incorrect Format";
}
}
<p>Please enter your course information in the following format AAA.111#2222_aa-1234:</p>
<input type ="text" name ="course" id="course" />
<button onclick="isValid()">Validate</button>
<p id="output"></p>
You had a few syntax errors:
return (myRegExp.test(text); should be return myRegExp.test(text);
isValid(document.getElementById("course".value) should be isValid(document.getElementById("course").value)
And finally, putting the return statemenet before the rest of your code defeats the whole purpose of the rest of your code. return breaks out of your current function, which means the if else statement is rendered useless.
function isValid(text) {
var myRegExp = "/([A-Z]{3})\.\d{3}#\d{4}_(sp|su|fa)-\d{4}/";
return myRegExp.test(text);
if (isValid(document.getElementById("course").value)) {
document.getElementById("output").innerHTML = "Correct Format";
} else {
document.getElementById("output").innerHTML = "Incorrect Format"
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 6 Assignment</title>
</head>
<body>
<p>Please enter your course information in the following format AAA.111#2222_aa-1234:</p>
<input type="text" name="course" id="course" />
<button onclick="isValid()">Validate</button>
<p id="output"></p>
<script src="registerFourth.js"></script>
</body>
</html>
There are a couple of syntax as well as function construction issues with this.
You have a missing ) in 2 lines -
return (myRegExp.test(text);
and
if (isValid(document.getElementById("course".value) line
You are also returning the value before the conditional statement. So the block below, will never run. Returning a function value ends the function execution
if (isValid(document.getElementById("course".value) {
document.getElementById("output").innerHTML = "Correct Format";
} else {
document.getElementById("output").innerHTML = "Incorrect Format"
}
Think about functions in terms of inputs and outputs and what function it performs.
For example,
/// this function only takes a string and tests if it matches the regex
/// input: string
/// output: true / false (boolean)
function testRegex(text) {
var myRegExp = /([A-Z]{3})\.\d{3}#\d{4}_(sp|su|fa)-\d{4}/;
return myRegExp.test(text)
}
/// this function runs when the button is clicked, calls the testRegex fn
/// and handles setting the output element
/// note: read about ternary conditional operators if confused about ?:
function isValid() {
const outputEL = document.getElementById("output")
const courseEl = document.getElementById("course")
outputEl.innerHTML = testRegex(courseEl.value) ? "Correct Format" : "Incorrect Format";
}
If you want to understand how the code is being executed -
the script tags loads your registerFourth.js which will contain the two functions I defined above - isValid and testRegex. Note that the functions are just defined and not executed yet
when you click the button, the isValid function starts executing
the isValid function gets the output element and course element
isValid then calls testRegex with the value of course element
now, testRegex runs with the value provided to it and returns (to the calling function, isValid is this case) a boolean value, based on if the value is valid
isValid is back in power and depending on the value testRegex sent it, it sets outputEl to CorrectFormat / Incorrect Format
isValid ends!
You miss a few closed brackets.
See updated RegExp .
Change document.getElementById("course".value) to document.getElementById("course").value
You use of return incorrectly, in my code no need return .
see full code :
function isValid() {
var text = document.getElementById("course").value;
var myRegExp = /^([A-Z]{3})\.\d{3}#\d{4}_(sp|su|fa|aa)-\d{4}$/;
document.getElementById("output").innerHTML = myRegExp.test(text) ? "Correct Format" : "Incorrect Format" ;
}
<p>Please enter your course information in the following format AAA.111#2222_aa-1234:</p>
<input type ="text" name ="course" id="course" />
<button onclick="isValid()">Validate</button>
<p id="output"></p>
this line is invalid
return (myRegExp.test(text);
If you want to return if the test is true
if (myRegExp.test(text)) return;
You also need to close the () here with 2 more )
if (isValid(document.getElementById("course").value))
That should solve your syntax issues. Not your logic though...

Retrieving strings in Parse

I am trying to retrieve two strings from my Parse Customers class. I want to compare these strings (usernameAdmin, and passwordAdmin respectively) with the input field entered by the user, and if they matched it will take them to a specific page.
I am taking this approach for a particular reason, and would appreciate feedback.
$scope.logIn = function(form) {
var Customer = Parse.Object.extend("Customers");
parseAdminUsername = Customer.get('usernameAdmin');
parseAdminPassword = Customer.get('passwordAdmin');
if (form.lusername == parseAdminUsername && form.lpassword == parseAdminPassword) {
window.location = 'adminSelect.php'
} else {
alert('error');
}
};
The html code looks as follow:
<form role="form" ng-show="scenario == 'Sign up'">
<h4 id="wrongCredentials"></h4>
<input id="signupformItem" ng-model="user.lusername" type="email" name="email" placeholder="Email Address"> <br>
<input id="signupformItem" ng-model="user.lpassword" type="password" name="password" placeholder=" Password"> <br>
<br>
<button id="signupbuttonFinal" ng-click="logIn(user)" class="btn btn-danger"> Sign In</button>
</form>
I receive the following error on console:
undefined is not a function
at Object.$scope.logIn
below is the line
parseAdminUsername = Customer.get('usernameAdmin');
You are better off using Parse in built users instead of creating a separate object and then you would use Parse.User.logIn.
If you were to use your table instead. Customer.get('usernameAdmin') is used to return a field after you have performed a query to return records/s. You are best to perform a find query to check the username and password like so:
var Customer = Parse.Object.extend("Customers");
var query = new Parse.Query(Customer);
query.equalTo("usernameAdmin", form.lusername);
query.equalTo("passwordAdmin", form.lpassword);
query.find({
success: function(results) {
if (results.length > 0) {
window.location = 'adminSelect.php';
}
},
error: function(error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
I'd recommend not to use window and instead $window so that you can unit test your code. Better yet use angular routing and create a Single page app.

Passing the value of a button into a text field

I'm having some trouble with getting Javascript to pass a value (which is stored in local storage) into a textfield. Ideally, I'd like for someone to be able to click the 'apply here' button on one page, have the job number stored in local storage and then have it auto-populate the job number field on my application page with the job number.
This is what I've got so far, I have a feeling that I haven't assigned things correctly.
html (on submit page)
<p>
<form id="applyjob1" action="enquire.html" method="get">
<input type="submit" id="job1" value="Apply for Job" />
</form>
</p>
html (field I'm trying to put data into)
Job Reference Number <input required="required" id="jobNo" name="jobno" type="text" /> </br />
Javascript
window.onload = function init() {
var jobID = document.getElementById("job"); /*button name */
jobID.onsubmit = passJob; /*executes passJob function */
}
function passJob(){
var jobSubmit = localstorage.jobID("1984"); /*assigns localstorage*/
if (jobSubmit != undefined){
document.getElementById("jobNo").value = localstorage.jobID;
}
I think this code would work for your fuction.
function passJob(){
localStorage.setItem("jobID", "1984");
if (localStorage.jobID != undefined) {
document.getElementById("jobNo").value = localStorage.jobID;
}
}
You are assigning the jobSubmit wrongly. To set item, use localStorage.setItem('key', value). Note the casing as it matters.
So basically you should do
var jobSubmit = localStorage.setItem(,"jobID", "1984"); // assigns jobSubmit
And I don't see any element with id="job"

javascript function inside function

I have just started with JavaScript and want to validate a form. All the tutorials I've found create an alert for feedback, but I'd like to use onblur and give an error message next to the field. I managed to do the two functions separately but can't merge them. I'd really appreciate your help!
This is what I came up with, but it doesn't do what I need:
function validateFirstName()
{
var x=document.forms["demo"]["firstname"].value;
if (x==null || x=="" || x==)
{
function addMessage(id, text)
{
var textNode = document.createTextNode(text);
var element = document.getElementById(id);
element.appendChild(textNode);
document.getElementById('firstname').value= ('Firstname must be filled out')
}
return false;
}
}
So the following is a simple way to validate a form field by checking the value of an input when the form is submitted. In this example the error messages are just sent to the div element about the form but this should still help you out.
The HTML code looks something like this:
<div id="errors"></div>
<form onSubmit="return validate(this);">
<input type="text" name="firstName" placeholder="What's your first name?">
<button type="submit" value="submit">Submit</button>
</form>
The Javascript code looks something like this:
function validate(form) {
var errors ='';
if(form.firstName.value =="") {
errors += '<li>Please enter your first name</li>';
}
if(errors !='') { //Check if there are any errors, if there are, then continue
var message = document.getElementById("errors"); //assigns the element with the id of "errors" to the variable "message"
message.innerHTML = "<ul>" + errors + "</ul>"; //adds the error message into a list with the error message into the HTML
return false;
} else {
return true;
}
}
Once you understand this you should be able to figure the rest out on your own or go to http://www.w3schools.com/ and check out the javascript section to help you out.
I'm not sure what you really looking for. If I understood right (and I can be very wrong) you are looking for something like:
var x = undefined; // Can be undefined, null, or empty string
if (x==null || x=="" || x==undefined) { // do no forget to check for undefined
function addMessage(id, text) {
// Your validation code goes here
alert(id + text);
};
addMessage(1234, "Mandatory field!");
}
Note, there are several ways to do it. I just showing the simplest way I can think of...

Categories