Getting data from the HTML form into JavaScript - javascript

I am trying to get the values from the form inputs once you click submit into variables in JavaScript.
However I don't seem to be having much luck as the console log just shows the variables as empty.
HTML
<html>
<head>
<meta charset="UTF-8">
<title>Registration</title>
</head>
<body>
<fieldset><legend>Registration</legend>
<form action="#" method="post" id="theForm">
<label for="username">Username<input type="text" name="username" id="username"></label>
<label for="name">Name<input type="text" name="name" id="name"></label>
<label for="email">Email<input type="email" name="email" id="email"></label>
<label for="password">Password<input type="password" name="password" id="password"></label>
<label for="age">Age<input type="number" name="age" id="age"></label>
<input type="hidden" name="unique" id="unique">
<input type="submit" value="Register!" id="submit">
</form>
</fieldset>
<div id="output"></div>
<script src="js/process.js"></script>
</body>
</html>
JS
var output = document.getElementById('output');
function addUser() {
'use strict';
var username = document.getElementById('username');
var name = document.getElementById('name');
var email = document.getElementById('email');
var password = document.getElementById('password');
var age = document.getElementById('age');
console.log(username.value);
console.log(name.value);
console.log(password.value);
}
// Initial setup:
function init() {
'use strict';
document.getElementById('theForm').onsubmit = addUser();
} // End of init() function.
//On window load call init function
window.onload = init;
EDIT It was because I needed to remove () on addUser and also add return false to the addUser function at the bottom.

In
function init() {
'use strict';
document.getElementById('theForm').onsubmit = addUser();
}
This will set the onsubmit equal to undefined because addUser returns nothing.
To get the function addUser as the onsubmit function use this instead.
function init() {
'use strict';
document.getElementById('theForm').onsubmit = addUser;
}
You are trying to pass the function itself not the return of it.
Also, when I'm making functions that will be passed or set, I find it more reasonable to write them like this:
var addUser = function(){
...
}

In order to make your function working, you might want to do this:
function init() {
'use strict';
document.getElementById('theForm').onsubmit = function () { addUser(); }
}
You can refer to the post below for further explanation:
Timing of button.onclick execution
Hope it helps!

Related

knockoutjs using module pattern not working

I am trying to create simple knockout example using module pattern
var login = {}; //login namespace
//Constructor
login.UserData = function () {
var self = this;
self.UserName = ko.observable("");
self.Password = ko.observable("");
};
//View-Model
login.UserVM = function () {
this.userdata = new login.UserData(),
this.apiUrl = 'http://localhost:9090/',
this.authenticate = function () {
var data = JSON.parse(ko.toJSON(this.userdata));
var service = apiUrl + '/api/Cryptography/Encrypt';
DBconnection.fetchdata('POST', service, JSON.stringify(data.Password), response, function () { console.log('Cannot fetch data') }, null, true);
function response(res) {
console.log(res)
}
}
return {
authenticate: this.authenticate
}
}();
$(function () {
ko.applyBindings(login.UserVM); /* Apply the Knockout Bindings */
});
HTML CODE:
<form id="loginform" name="loginForm" method="POST">
<div id="form-root">
<div>
<label class="form-label">User Name:</label>
<input type="text" id="txtFirstName" name="txtFirstName" data-bind="value:login.UserData.UserName" />
</div>
<div>
<label class="form-label">Password:</label>
<input type="text" id="txtLastName" name="txtLastName" data-bind="value:login.UserData.Password" />
</div>
<div>
<input type="button" id="btnSubmit" value="Submit" data-bind="click: authenticate" />
</div>
</div>
</form>
the problem is am not able to get userdata in the viewmodel on click of submit it is returning undefined and the login object holds the changed value of textbox but on click it is returning black values.
please let me know
Also can you let me know how to implement definative module pattern in the same code.
The object you are returning from login.UserVM has only authenticate property and doesn't have userdata or apiUrl properties. So, instead using an IIFE to create an object, set login.UserVM to a constructor function similar to login.UserData. And then use new operator to create the viewModel object. Now the viewModel will have userdata and apiUrl properties (remove the return from the function)
Also, you need to change the HTML bindings to: data-bind="value:userdata.UserName". This looks for the userdata property inside the bound viewModel
var login = {}; //login namespace
//Constructor
login.UserData = function () {
var self = this;
self.UserName = ko.observable("");
self.Password = ko.observable("");
};
//View-Model
login.UserVM = function () {
this.userdata = new login.UserData(),
this.apiUrl = 'http://localhost:9090/',
this.authenticate = function () {
var data = JSON.parse(ko.toJSON(this.userdata));
console.log(data)
//var service = this.apiUrl + '/api/Cryptography/Encrypt';
//DBconnection.fetchdata('POST', service, JSON.stringify(data.Password), response, function () { console.log('Cannot fetch data') }, null, true);
function response(res) {
console.log(res)
}
}
}; // remove the () from here
ko.applyBindings(new login.UserVM()); /* Apply the Knockout Bindings */
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<form id="loginform" name="loginForm" method="POST">
<div id="form-root">
<div>
<label class="form-label">User Name:</label>
<input type="text" id="txtFirstName" name="txtFirstName" data-bind="value:userdata.UserName" />
</div>
<div>
<label class="form-label">Password:</label>
<input type="text" id="txtLastName" name="txtLastName" data-bind="value:userdata.Password" />
</div>
<div>
<input type="button" id="btnSubmit" value="Submit" data-bind="click: authenticate" />
</div>
</div>
</form>

Javascript " onsubmit " Event Not Working Correctly

I am just practicing js. I am trying to make a very simple validation in form but it came with, as i was expecting, an error.
Here's my code :
var form = document.getElementById('form');
var name = document.getElementById('name');
var email = document.getElementById('email');
var msg = document.getElementById('message');
var error = document.getElementById('error');
function handlingForm() {
form.onsubmit = function(c)
{
if (name.value == "")
{
error.innerHTML = "Error Submiting Form !";
return false;
}
else
{
error.innerHTML = "You have successfuly submited the Form..! Congrats ;)";
return true; // ;) Just Kidding :D
}
};
}
window.onload = function(c)
{
handlingForm();
}
<!DOCTYPE html>
<html>
<head>
<title>jsForm</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="container">
<form id="form">
<input type="text" placeholder="Name" id="name">
<input type="text" placeholder="Email" id="email">
<textarea rows="4" placeholder="Message" id="message"></textarea>
<input type="submit" value="Send" id="send">
<p id="error"></p>
</form>
</div>
<script src="script.js"></script>
</body>
</html>
The problem is that, it doesn't validate it. Every time it returns true on submitting but when i replace the " name.value" with "email.value" the code works. I don't know now what's the problem actually. If someone could help me..
It looks like the input with id name is not created in DOM by the time of JavaScript execution.
You can resolve that by putting the code in the window.onload code block or inside the form.onsubmit
var form = document.getElementById('form');
var email = document.getElementById('email');
var msg = document.getElementById('message');
var error = document.getElementById('error');
function handlingForm() {
form.onsubmit = function(c) {
var name = document.getElementById('name');
if (name.value == "") {
error.innerHTML = "Error Submiting Form !";
return false;
} else {
error.innerHTML = "You have successfuly submited the Form..! Congrats ;)";
return true; // ;) Just Kidding :D
}
};
};
handlingForm();
<div id="container">
<form id="form">
<input type="text" placeholder="Name" id="name">
<input type="text" placeholder="Email" id="email">
<textarea rows="4" placeholder="Message" id="message"></textarea>
<input type="submit" value="Send" id="send">
<p id="error"></p>
</form>
</div>
Your variable called name is a problem. It's not working because name is a predefined identifier in some implementations. Though it's not a reserved keyword, it's best practice to avoid using it as a variable name.
Rename it to name_ (or almost anything else) and it will work.
If name.value has no value, it is undefined. So undefined !== "", which is why it will never be true. Just do a null check for name.value. Also, you need to move name inside of that function since the first time it is called, value will always be undefined:
var form = document.getElementById('form');
var email = document.getElementById('email');
var msg = document.getElementById('message');
var error = document.getElementById('error');
function handlingForm() {
form.onsubmit = function(c)
{
var name = document.getElementById('name');
if (!name.value)
{
error.innerHTML = "Error Submiting Form !";
return false;
}
else
{
error.innerHTML = "You have successfuly submited the Form..! Congrats ;)";
return true; // ;) Just Kidding :D
}
};
}
window.onload = function(c)
{
handlingForm();
}
<!DOCTYPE html>
<html>
<head>
<title>jsForm</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="container">
<form id="form">
<input type="text" placeholder="Name" id="name">
<input type="text" placeholder="Email" id="email">
<textarea rows="4" placeholder="Message" id="message"></textarea>
<input type="submit" value="Send" id="send">
<p id="error"></p>
</form>
</div>
<script src="script.js"></script>
</body>
</html>
Try this:
window.onload = handlingForm();
Why your function has c parameter?
This is due to a quirk of how global variables are handled in web pages. Each one is treated as a property of the window object, so when you assign to email, you're actually creating and assigning to window.email, and so on.
However, some properties of the window object already exist and have special meaning to the browser, such as window.location (the current URL) and window.name (used in cross-frame link targets).
To see it in practice, do this in the global scope (outside any function):
var location; // should be undefined, right?
alert(location); // but it's actually window.location
Because of the special meaning of window.name, anything you assign to it (or to global name) will be converted into a string. The element that you try to store becomes a string, and so no longer works as an element.
To fix it, simply move your code into a function, so that the variables are local and no longer have this strange behaviour. You can use your window.onload function for this.

using $watch in angularjs

I have a form with 2 input fields and requirement is that once user enters valid data into these
fields, I need to pass the input data to the factory function and get the data from server.To achieve this I thought of using $watch function but stuck at how to know if form is valid in $wathc function and then call the factory function to get data from the server.Here is the code.
Any help would be highly appreciated.
//html
<html>
<body ng-app="myModule">
<div ng-controller="myCtrl">
Product Id: <input type="text" ng-model="myModel.id" /><br/>
Product Name: <input type="text" ng-model="myModel.productname" /><br/>
</div>
</body>
</html>
//js
var myModule = angular.module('myModule',[]);
myModule.controller('myCtrl',['$scope', function($scope){
$scope.myModel = {};
var getdata = function(newVal, oldVal) {
};
$scope.$watch('myModel.id', getdata)
$scope.$watch('myModel.productname', getdata)
}]);
Wouldn't you just watch myModel, since the same function is called in both cases?
You could do this with ng-change just as easily.
<html>
<body ng-app="myModule">
<form name="productForm" ng-controller="myCtrl">
<div>
Product Id: <input type="text" name="idModel" ng-model="myModel.id" ng-change="validateID()" /><br/>
Product Name: <input type="text" ng-model="myModel.productname" ng-change="validateProduct()" /><br/>
</div>
</form>
</body>
And your JS would look like this:
var myModule = angular.module('myModule',[]);
myModule.controller('myCtrl',['$scope', 'myFactory',
function($scope, myFactory){
$scope.myModel = {};
$scope.validateID = function(){
//things that validate the data go here
if(your data is valid){
myFactory.get(yourParams).then(function(data){
//whatever you need to do with the data goes here
});
}
};
$scope.validateProduct = function(){
//things that validate the data go here
if(your data is valid){
myFactory.get(yourParams).then(function(data){
//whatever you need to do with the data goes here
});
}
};
}
]);
Using ng-change saves you from having to add a $watch to your scope (they are expensive) and will fire when the user leaves the input box. If you need to catch each keystroke, I would recommend that you use UI-Keypress and run the same functions.
To know if form is valid you have to add a form tag and inside your controller check $valid, on your example the form is always valid becaus you do not have any required field.
See the below example on codepen
The HTML
<div ng-app="myModule">
<div ng-controller="myCtrl">
<form name="myform" novalidate>
Product Id:
<input type="text" ng-model="myModel.id" />
<br/>
Product Name:
<input type="text" ng-model="myModel.productname" />
<br/>
</form>
<br/>
<div>{{result}}</div>
<div>Form is valid: {{myform.$valid}}</div>
</div>
</div>
The JS
var myModule = angular.module('myModule', []);
myModule.controller('myCtrl', ['$scope', function ($scope) {
$scope.myModel = {};
$scope.result = "(null)";
var getdata = function (newVal, oldVal) {
var valid = null;
if ($scope.myform.$valid) {
valid = "is valid";
} else {
valid = "is INVALID";
}
$scope.result = "Changed value " + newVal + " form " + valid;
};
$scope.$watch('myModel.id', getdata);
$scope.$watch('myModel.productname', getdata);
}]);

javascript form validation object

Please i just started learning javascript, In order to build my skill. I gave myself a javascript project to build an object validator.The first method i created is checkEmpty. This method check for empty field. But for reason unknow to me the method don't work.
This is the html form
<form name="myForm">
<input type="text" class="required email" name='fName'/>
<input type="text" class="required number" name="lName"/>
<input type="submit" value="submit" name="submit" id="submit"/>
</form>
This is the javascript that called the validator object
window.onload = function(){
var validate = new FormValidator('myForm');
var submit = document.getElementById('submit');
//this method won't work for internet explorer
submit.addEventListener('click',function(){return checkLogic();},false);
var checkLogic = function(){
validate.checkEmpty('fName');
};
}
This is the javascript object called Formvalidation
function FormValidator(myForm){
//check ur error in stack overflow;
this.myForm = document.myForm;
this.error = '';
if(typeof this.myForm === 'undefined'){
alert('u did not give the form name ');
return;
}
}
//this method will check wheather a field is empty or not
FormValidator.prototype.checkEmpty = function(oEmpty){
var oEmpty = this.myForm.oEmpty;
if(oEmpty.value === '' || oEmpty.value.length === 0){
this.error += "Please Enter a valid Error Message \n";
}
FormValidator.printError(this.error);
};
This method printout the error;
FormValidator.printError = function(oData){
alert(oData);
};
After formatting your code it got a lot easier to find out what went wrong. I assume you are trying to validate the input fields from your html code.
Your code is falling on its nose the first time in line 1 of the method checkEmpty():
FormValidator.prototype.checkEmpty = function(oEmpty){
var oEmpty = this.myForm.oEmpty;
if(oEmpty.value === '' || oEmpty.value.length === 0){
this.error += "Please Enter a valid Error Message \n";
}
FormValidator.printError(this.error);
};
In the first line you are hiding the methods argument oEmpty with the var oEmpty statement from line 1
There are several other issues like overusing methods and members. The following code is probably what you wanted:
1.) index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<form name="myForm">
<input id="fName" name='fName' type="text"/>
<input id="lName" name="lName" type="text"/>
<input id="submit" name="submit" type="submit" value="submit"/>
</form>
<script src="main.js"></script>
</body>
</html>
2.) main.js
function InputFieldValidator(inputFieldName){
this.inputFieldName = inputFieldName;
this.inputField = document.getElementById(this.inputFieldName);
if(this.inputField === 'undefined'){
alert('No input field: ' + this.inputFieldName);
}
}
InputFieldValidator.prototype.validate = function(){
if(this.inputField.value === ''){
alert('Please enter valid text for input field: ' + this.inputFieldName);
}
};
window.onload = function(){
var fNameValidator = new InputFieldValidator('fName'),
lNameValidator = new InputFieldValidator('lName'),
submitButton = document.getElementById('submit');
submitButton.addEventListener('click', function (){
fNameValidator.validate();
lNameValidator.validate();
});
};
If you like you can wrap the input field validators from above easily in a form validator.
This is the right way to define functions this way:
var FormValidator = function(myForm){ /* function body */ };
FormValidator.prototype.checkEmpty = function(oEmpty){ /* function body */ };
Than, after instantiating the object, you can call FormValidator.checkEmpty(value) like you did.

Javascript Error Null is not an Object

Im getting a error in the Web Inspector as shown below:
TypeError: 'null' is not an object (evaluating 'myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
return false;
}')
Here is my Code (HTML):
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>
<script src="js/script.js" type="text/javascript"></script>
<form>
<input type="text" id="myTextfield" placeholder="Type your name" />
<input type="submit" id="myButton" value="Go" />
</form>
Here is the JS:
var myButton = document.getElementById("myButton");
var myTextfield = document.getElementById("myTextfield");
function greetUser(userName) {
var greeting = "Hello " + userName + "!";
document.getElementsByTagName ("h2")[0].innerHTML = greeting;
}
myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
return false;
}
Any Idea why I am getting the error?
Put the code so it executes after the elements are defined, either with a DOM ready callback or place the source under the elements in the HTML.
document.getElementById() returns null if the element couldn't be found. Property assignment can only occur on objects. null is not an object (contrary to what typeof says).
Any JS code which executes and deals with DOM elements should execute after the DOM elements have been created. JS code is interpreted from top to down as layed out in the HTML.
So, if there is a tag before the DOM elements, the JS code within script tag will execute as the browser parses the HTML page.
So, in your case, you can put your DOM interacting code inside a function so that only function is defined but not executed.
Then you can add an event listener for document load to execute the function.
That will give you something like:
<script>
function init() {
var myButton = document.getElementById("myButton");
var myTextfield = document.getElementById("myTextfield");
myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
}
}
function greetUser(userName) {
var greeting = "Hello " + userName + "!";
document.getElementsByTagName ("h2")[0].innerHTML = greeting;
}
document.addEventListener('readystatechange', function() {
if (document.readyState === "complete") {
init();
}
});
</script>
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>
<form>
<input type="text" id="myTextfield" placeholder="Type your name" />
<input type="button" id="myButton" value="Go" />
</form>
Fiddle at - http://jsfiddle.net/poonia/qQMEg/4/
Try loading your javascript after.
Try this:
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>
<form>
<input type="text" id="myTextfield" placeholder="Type your name" />
<input type="submit" id="myButton" value="Go" />
</form>
<script src="js/script.js" type="text/javascript"></script>
I think the error because the elements are undefined ,so you need to add window.onload event which this event will defined your elements when the window is loaded.
window.addEventListener('load',Loaded,false);
function Loaded(){
var myButton = document.getElementById("myButton");
var myTextfield = document.getElementById("myTextfield");
function greetUser(userName) {
var greeting = "Hello " + userName + "!";
document.getElementsByTagName ("h2")[0].innerHTML = greeting;
}
myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
return false;
}
}
I agree with alex about making sure the DOM is loaded. I also think that the submit button will trigger a refresh.
This is what I would do
<html>
<head>
<title>webpage</title>
</head>
<script type="text/javascript">
var myButton;
var myTextfield;
function setup() {
myButton = document.getElementById("myButton");
myTextfield = document.getElementById("myTextfield");
myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
return false;
}
}
function greetUser(userName) {
var greeting = "Hello " + userName + "!";
document.getElementsByTagName("h2")[0].innerHTML = greeting;
}
</script>
<body onload="setup()">
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>
<form>
<input type="text" id="myTextfield" placeholder="Type your name" />
<input type="button" id="myButton" value="Go" />
</form>
</body>
</html>
have fun!

Categories