Calling class function not responding as expected - javascript

I have a problem with calling the variable valio, when I put text into the input and after calling it, the console returns "now registered
undefined".
I have experience with this type of calling but never happened before so could some one explain me why this doesn't work as I expected ?
var name = document.getElementById("name");
var email = document.getElementById("email");
var comment = document.getElementById("comment");
class User{
constructor(username,comment,email){
this.username = username;
this.comment = comment;
this.email = email;
}
register(){
console.log(this.username + this.comment + " is now registered");
}
}
var valio = new User(name.value , comment.value, email.value);
<input id="name" type="text" value=""><br>
<input id="email" type="text" value=""><br>
<input id="subject" type="text" value=""><br>
<input id="comment" type="text" value=""><br>

Change ur variable name to uname.
var uname = document.getElementById("name");
var email = document.getElementById("email");
var comment = document.getElementById("comment");
class User{
constructor(username,comment,email){
this.username = username;
this.comment = comment;
this.email = email;
}
register(){
console.log(this.username + this.comment + " is now registered");
}
}
var valio = new User(uname.value , comment.value, email.value);
<input id="name" type="text" value=""><br>
<input id="email" type="text" value=""><br>
<input id="subject" type="text" value=""><br>
<input id="comment" type="text" value=""><br>

You put the reference to the name input field in a variable called name. However, name is already defined as a global variable of type string:
https://developer.mozilla.org/en-US/docs/Web/API/Window/name
It can probably not be overridden.
Try changing the variable name:
var username = document.getElementById("name");
var valio = new User(username.value , comment.value, email.value);

It appears that the name variable is conflicting with a keyword in javascript. Try renaming it to something else.
e.g.
var nameInput = document.getElementById("name");
Then pass in nameInput.value to the constructor.

Related

HTML JS manual form validation not working

I'm trying to manually validate a form in HTML/CSS/JS. At the very basic level, I want to ensure that the user cannot input blank values for first name and last name. The problem is that whenever I try to change or update the inputs to what the user has written, it doesn't save. Everything remains "null". It's also extremely frustrating that in my JS code when I'm trying to use an IF statement to check if the first name has no value or is null, I get an immediate error message that "first" is null, because its null no matter what, if you input something or not, but it doesn't even complete it's job. I'm using the if statement to CHECK if its null, not for it to do something with it, so why is it having an issue simply following the code below it if the condition is true? I've sat on this for like an hour and its becoming unbearable. I'm new to JS and Im really not getting how something as simple as IF statements isn't working for me.
HTML form:
<form action="" method="get" id="my-form">
<h1>Contact Us</h1>
<div class="txtb">
<label>First Name :</label>
<input type="text" id = "firstname" placeholder="Enter Your First Name">
</div>
<div class="txtb">
<label>Last Name :</label>
<input type="text" id = "lastname" placeholder="Enter Your Last Name">
</div>
<div class="txtb">
<label>Email :</label>
<input type="email" id = "email" placeholder="Enter Your Email" required>
</div>
<div class="txtb">
<label>Date Visited :</label>
<input type="date" id = "date" required>
</div>
<div class="txtb">
<label>What did you think of it when you visited? :</label>
<textarea id = "msg" required></textarea>
</div>
<button type='submit'>Submit</button>
<!--onclick = form.submit()-->
</form>
</div>
<div id="error"></div>
New JS:
let first = document.getElementById("firstname").value;
let last = document.getElementById("lastname").value;
let email = document.getElementById("email").value;
let msg = document.getElementById("msg").value;
let date = document.getElementById("date").value;
let form = document.getElementById("my-form");
let errorEl= document.getElementById("error");
function formChanged() {
first = document.getElementById("firstname");
last = document.getElementById("lastname");
email = document.getElementById("email");
msg = document.getElementById("msg");
date = document.getElementById("date");
console.log(first,last,email,msg,date,form)
}
form.addEventListener('submit', (e) => {
let messages = []
console.log(first, last)
if (first === '' || first == null){
messages.push('First name is required')
}
if (last === '' || last == null){
messages.push('Last name is required')
}
if (messages.length>0){
e.preventDefault()
errorEl.innerText = messages.join(', ')
}
console.log(first, last)
})
//window.alert(messages)
If anyone knows a better way to do this manually also, it would be greatly appreciated if you could share it. At this point, everything works except the messages array remains the same, so I'm going to add something to remove the messages if first doesn't == null or ''
Edit :
You are doing first = document.getElementById("firstname").value; so it get by ID but you don't have any id.
For example, change
<input type="text" name = "firstname" placeholder="Enter Your First Name">
to
<input type="text" id="firstname" name="firstname" placeholder="Enter Your First Name">
Notice the id="firstname".
Original Answer :
Your function
function formChanged() {
first = document.getElementById("firstname").value;
last = document.getElementById("lastname").value;
email = document.getElementById("email").value;
msg = document.getElementById("msg").value;
date = document.getElementById("date").value;
console.log(first,last,email,msg,date,form)
}
Is setting first to document.getElementById("firstname").value; while you first initialized it to
let first = document.getElementById("firstname");.
Notice, that in your function you set it to the input's .value, not the input itself.
So if (first.value === '' || first.value == null) won't work because first is already equal to .value thus you are in fact doing document.getElementById("firstname").value.value which is undefined !
Try either :
to change formChanged variable initialisation to document.getElementById("firstname")
OR
change the if to if (first == '' || first== null)
Adding on to what Sorikairo said:
From this answer, add a return value to your onsubmit instead of preventDefault:
if (messages.length>0){
// e.preventDefault()
return false;
errorEl.innerText = messages.join(', ')
}
return true;
SOLVED:
If you run into this problem, check all of your .value lines, because doubling them up or not having enough was the main problem here. Everything was being checked against the wrong things. I also recommend console.log() ing everything you do like I did just for variable tracking.
Final JS:
let first = document.getElementById("firstname").value;
let last = document.getElementById("lastname").value;
let email = document.getElementById("email").value;
let msg = document.getElementById("msg").value;
let date = document.getElementById("date").value;
let form = document.getElementById("my-form");
let errorEl= document.getElementById("error");
function formChanged() {
first = document.getElementById("firstname").value;
last = document.getElementById("lastname").value;
email = document.getElementById("email").value;
msg = document.getElementById("msg").value;
date = document.getElementById("date").value;
form= document.getElementById("my-form");
errorEl = document.getElementById("error");
console.log(first,last,email,msg,date,form)
}
form.addEventListener('submit', (e) => {
formChanged()
errorEl.innerText = '';
var messages = []
if (first === '' || first == null){
messages.push('First name is required')
}
if (last === '' || last == null){
messages.push('Last name is required')
}
if (messages.length>0){
e.preventDefault()
errorEl.innerText = messages.join(', ')
}
console.log(first, last)
console.log(messages)
})
//window.alert(messages)
Final HTML:
<form action="" method="get" id="my-form">
<h1>Contact Us</h1>
<div class="txtb">
<label>First Name :</label>
<input type="text" id = "firstname" placeholder="Enter Your First Name">
</div>
<div class="txtb">
<label>Last Name :</label>
<input type="text" id = "lastname" placeholder="Enter Your Last Name">
</div>
<div class="txtb">
<label>Email :</label>
<input type="email" id = "email" placeholder="Enter Your Email" required>
</div>
<div class="txtb">
<label>Date Visited :</label>
<input type="date" id = "date" required>
</div>
<div class="txtb">
<label>What did you think of it when you visited? :</label>
<textarea id = "msg" required></textarea>
</div>
<button type='submit'>Submit</button>
<!--onclick = form.submit()-->
</form>
</div>
<div id="error"></div>

Javascript, The <p> element displays [object HTMLInputElement] why does it display this?

I am trying to figure out Object Oriented Programming in javascript and instead of displaying the input on form it displays [object HTMLInputElement]
document.getElementById('submit').addEventListener('click', function() {
let uName = document.getElementById('uName').value;
info.showInfo();
});
class Information {
constructor(name) {
this.name = name;
}
showInfo() {
var z = document.createElement('p');
z.innerHTML = this.name;
document.body.appendChild(z);
}
}
const info = new Information(uName);
<form action="/home.php" method="get"></form>
<label for="fname">First name:</label>
<input type="text" name="name" id="uName" value="value" />
<button id="submit">Submit</button>
As #Teemu said in comment let uName is invisible for const info = new Information(uName);
Try following code.
uNameElement = document.getElementById('uName');
document.getElementById('submit').addEventListener('click', function() {
const info = new Information(uNameElement.value);
info.showInfo();
});
class Information {
constructor(name) {
this.name = name;
}
showInfo() {
var z = document.createElement('p');
z.textContent = this.name;
document.body.appendChild(z);
}
}
<form action="/home.php" method="get"></form>
<label for="fname">First name:</label>
<input type="text" name="name" id="uName" value="value" />
<button id="submit">Submit</button>
UPDATE: z.innerHTML replaced by z.textContent

How to pass form data to GAS

I am trying to pass data from a form into a Google Apps Script but when I press submit I am greeted by I blank screen.
Form:
<div id="nameDiv">
<form action="https://script.google.com/a/umbc.edu/macros/s/AKfycbztum1ImJZeXXYt0fFhwOAMUsB5zCsJQohrum4W7qiH/dev">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" >
<input type="submit" value="Submit" onclick="google.script.run.nameSearch()">
</form>
</div>
Script:
function nameSearch(){
try {
var firstName = document.getElementById("fname").value
var lastName = document.getElementById("lname").value
var inputSheet = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z3j7wxMLsXilyKDIH7XnE7VNQqF66fIH4B-mmuWwCJ8/edit#gid=1235654559");
var inputData = inputSheet.getDataRange().getValues();
for (var i = 1; i < inputData.length; i++) {
if (inputData[i][10] == firstName && inputData[i][11] == lastName) {
var result = inputData[i][14] + ": " + inputData[i][15]
}
}
document.getElementById('nameDiv').innerHTML =
"<center>Last Name:" + lastName + "</center>" +
"</br><center>First Name:" + firstName + "</center>"
} catch(e) {
alert(e)
}
}
I am trying to pass this data to the script so that it can use it to search a google sheet so I cannot just place the script in the html as a client side script. Any thought?
All the HTML-related methods (getElementById, innerHTML, etc.) should be in client-side script, and Apps Script methods should be in the server-side.
If I understand you correctly, you want to do the following:
When this form gets submitted, look for the row whose columns K and L match the inputted fields (indexes 10 and 11 from inputData array).
For this row, return data from columns O and P (indexes 14 and 15 from inputData array).
Write this returned data to the HTML.
If all this is correct, then you could do this:
Add an onclick event in the submit input that will fire a client-side function (a function that is declared inside the tags in the HTML). There is no need to use a for this. The HTML body could be something like this:
<div id="nameDiv">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" >
<input type="submit" value="Submit" onclick="clientNameSearch()">
</div>
From this client-side function called clientNameSearch(), retrieve the values from fname and lname, and use these as parameters when you call a server-side function called nameSearch):
function clientNameSearch() {
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
google.script.run.withSuccessHandler(onSuccess).nameSearch(firstName, lastName);
}
This server-side function iterates through all rows with content in the spreadsheet, and returns the result for the first row whose columns K and L match the inputted data:
function nameSearch(firstName, lastName){
try {
var inputSheet = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z3j7wxMLsXilyKDIH7XnE7VNQqF66fIH4B-mmuWwCJ8/edit#gid=1235654559");
var inputData = inputSheet.getDataRange().getValues();
for (var i = 1; i < inputData.length; i++) {
if (inputData[i][10] == firstName && inputData[i][11] == lastName) {
var result = inputData[i][14] + ": " + inputData[i][15];
return result;
}
}
} catch(e) {
alert(e)
}
}
This result is then passed as a parameter to a client-side function called onSuccess via a success handler. This is necessary since server-side functions called by google.script.run don't return anything directly, as specified here. Then onSuccess writes the result to the HTML:
function onSuccess(result) {
document.getElementById('nameDiv').innerHTML = "<div>" + result + "</div>";
}
Full code:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div id="nameDiv">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" >
<input type="submit" value="Submit" onclick="clientNameSearch()">
</div>
</body>
<script>
function clientNameSearch() {
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
google.script.run.withSuccessHandler(onSuccess).nameSearch(firstName, lastName);
}
function onSuccess(result) {
document.getElementById('nameDiv').innerHTML = "<div>" + result + "</div>";
}
</script>
</html>
And the Code.gs would be like:
function nameSearch(firstName, lastName){
try {
var inputSheet = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z3j7wxMLsXilyKDIH7XnE7VNQqF66fIH4B-mmuWwCJ8/edit#gid=1235654559");
var inputData = inputSheet.getDataRange().getValues();
for (var i = 1; i < inputData.length; i++) {
if (inputData[i][10] == firstName && inputData[i][11] == lastName) {
var result = inputData[i][14] + ": " + inputData[i][15];
return result;
}
}
} catch(e) {
alert(e)
}
}
function doGet(e) {
return HtmlService.createHtmlOutputFromFile("your-html-name");
}
I'm not sure you want to write the result to the HTML, but in any case, at this point it shouldn't be difficult to modify this so that it writes exactly what you want and where you want.
Reference:
google.script.run.myFunction(...) (any server-side function)
withSuccessHandler(function)
I hope this is of any help.
Try this:
Launch the dialog fill the text boxes and click submit. The view logs and see the next dialog.
function launchADialog() {
var html='<form><br /><input type="text" name="Name" /> Name: <br /><input type="text" name="Age" /> Age: <br />';
html+='<select name="Children" ><option value="0">None</option><option value="1">One</option><option value="2">Two</option></select> Children:<br />';
html+='<input type="button" value="Submit" onClick="google.script.run.processForm(this.parentNode);" /></form>';
var userInterface=HtmlService.createHtmlOutput(html);
SpreadsheetApp.getUi().showModelessDialog(userInterface, "The Form");
}
function processForm(form) {
Logger.log(JSON.stringify(form));
var s=Utilities.formatString('<br />Name: %s <br />Age:%s <br />Number Of Children: %s', form.Name, form.Age, form.Children);
s+='<br /><input type="button" value="Close" onClick="google.script.host.close();" />';
var userInterface=HtmlService.createHtmlOutput(s);
SpreadsheetApp.getUi().showModelessDialog(userInterface, "Form Data")
}

Getting text from input form returns empty string, but console.log shows displays text

I know this is a commonly posted question so I apologize, but I've tried javascript, jQUERY, parts of this,several versions from previous work that DO work, .value, .textContent, .innerHTML, getAttribute('value'), document.getElementById and just everything else I could think of.
I console.log(user_name.value) and get the value I want, but when I console.log(name) or try to use user_name.value it's just an empty string. I'm new to development and got all the rest of the code working, everything else is hanging on this simple part and I can't solve it yet. Any help would be so appreciated.
HTML:
<form>
<input id="user_name" type="text" placeholder="Your Name" />
<input id="user_email" type="text" placeholder="Your E-mail" />
</form>
JavaScript:
var name;
var email;
function reserveSeat(name, seatNumber, email) {
var name = $('#user_name').getAttribute('value');
var email = $('#user_email').getAttribute('value');
var seatNumber = seatNumbers;
reservedSeats.push (new CustomerReservation (name, seatNumber, email));
console.log(name)
console.log(email)
};
$('.submitBtn').on('click', reserveSeat(name, seatNumber, email));
You tried all but the right one: val()
name = $('#user_name').val();
email = $('#user_email').val();
Note: if submitBtn is a type submit don't forget to prevent the default event,
$('.submitBtn').on('click', function(e){
e.preventDefault();
name = $('#user_name').val();
email = $('#user_email').val();
reservedSeats.push (new CustomerReservation (name, seatNumber, email));
console.log(name)
console.log(email)
});
Note2: if your form is dynamically added don't forget to delegate your event
there is no attribute called value in the input box and you are using jquery with javascript functions using ".val()" is the right option
Try this,
<form>
<input id="user_name" type="text" placeholder="Your Name" />
<input id="user_email" type="text" placeholder="Your E-mail" />
<input id="submitBtn" type="submit" class="submitBtn"/>
</form>
$(document).on('click','.submitBtn',function(){
var name = $('#user_name').val();
var email = $('#user_email').val();
console.log(name)
console.log(email)
});
please review this one
/*need gobal variable or not?? if not I will just remove it
var name;
var email; */
function reserveSeat(seatNumbers) {
/*for savety*/
seatNumber = Number(seatNumbers) || 5;
/* change getAttribute(value) to val()*/
var name = $('#user_name').val(),
email = $('#user_email').val();
reservedSeats.push(new CustomerReservation(name, seatNumber, email));
console.log(name);
console.log(email);
};
$('.submitBtn').on('click', reserveSeat(seatNumber));

TypeError: document.getElementById(...); is null in Javascript

All of my var statements uses identifiers:
var identifier = document.getElementById("somename");
So why am I getting a null error?
I ran this code in the Javascript runner and got the null error message. And in my browsers Firefox and Chrome I don't get any errors or warnings. When I run the code in the browser and click the button to activate the event handler, the form clears. It's not going to a server anyway. It's just practice. I'm taking a course in javascript and Dynamic HTML. If anybody care to look at my code and tell me what I'm doing wrong I'd appreciate it.
There's got to be something that I'm not getting right. Here is the script:
window.onload = function(){
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var loginName = document.getElementById("uname").value;
var myEmail = document.getElementById("email").value;
var pass1 = document.getElementById("password1").value;
var pass2 = document.getElementById("password2").value;
if(document.getElementById("uname").value == ""){
return false;
alert("Your user name can't be blank.");
};
if(pass1.value !== pass2.value){
get.documentElementById("signin").value.disabled = true;
return false;
alert("Please retype your password.");
}else if(pass1.value === pass2.value){
alert("Welcome!");
};
};
HTML
<body>
<form action = "" name = "form" method = "Post">
<label for="fname">First Name:</label><input type = "text" id = "fname"required></input>
<label for="lname">Last Name:</label><input type = "text" id = "lname" required></input>
<label for="uname">User Name:</label><input type = "text" id = "uname" required></input><br/>
<label for="password1">Password:</label><input type = "password" id = "password1"required ></input><br/>
<label for="password2">Verify Password:</label><input type = "password" id = "password2"required ></input><br/>
<label for="email">Email Address:</label><input type = "email" id = "email" required></input><br/>
<button type = "submit"id = "signin" onclick = "function()">Submit</button>
</form>
<script src="signUp.js"></script>
</body>
I cleaned up your code for you. There were several spots where you had errors (e.g., typing pass1.value instead of just pass1. This should work, but of course take time to study it to see what I changed and understand why. Here's a fiddle showing it working. Note that you should never expect this type of code to run in the "runners" that you've made reference to; the code here makes explicit reference to particular elements in the DOM, which the runners won't have. (Using a site like JSFiddle is better for this sort of thing, since you can put HTML into it as well).
var submitForm = function () {
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var loginName = document.getElementById("uname").value;
var myEmail = document.getElementById("email").value;
var pass1 = document.getElementById("password1").value;
var pass2 = document.getElementById("password2").value;
console.log(pass1, pass2);
if (document.getElementById("uname").value == "") {
alert("Your user name can't be blank.");
return false;
}
if (pass1 !== pass2) {
document.getElementById("signin").value.disabled = true;
alert("Please retype your password.");
return false;
} else if (pass1 === pass2) {
alert("Welcome!");
}
};
<body>
<form action="" name="form" method="POST">
<label for="fname">First Name:</label><input type ="text" id = "fname" required></input>
<label for="lname">Last Name:</label><input type = "text" id = "lname" required></input>
<label for="uname">User Name:</label><input type ="text" id ="uname" required></input><br/>
<label for="password1">Password:</label><input type="password" id="password1" required></input><br/>
<label for="password2">Verify Password:</label><input type="password" id="password2" required ></input><br/>
<label for="email">Email Address:</label><input type="email" id="email" required></input><br/>
<button type="submit" id="signin" onclick="submitForm()">Submit</button>
</form>
</body>

Categories

Resources