JavaScript - Forms, Object-Oriented Programming and Modern JavaScript Development WDD330📱
Forms
Forms are made up of a form element that contains form
controls such as input fields, select menus and buttons.
Forms cab be processed using JavaScript in the frontend, the DOM has property document.forms, returns a collection of forms using index notation.
document.forms
return and HTML collection of all the forms in the document in order they appear in the markup
const form = document.forms[0];
vs
const form = document.forms.search;
Access Control:
const input = form['searchInput']
Access Element:
const input = form['searchInput']
reset form:
form.reset()
submit form:
form.submit()
The placeholder
Attribute
Similar functionality can be produced in modern browsers using the placeholder attribute in the HTML markup. Simply change the input field to the following in search.html:
input type='text' name='search-box' placeholder='Search Here'
This has slightly different behavior in that the placeholder text is not actually a value of the input field, so it won’t be submitted as the field’s value if the user fails to fill it in.
EVENTS
change: moves focus after changing
submit: form is submitted
focus: element is focused on (cursor inside input)
blur: user moves focus away from form
NEW ATTRIBUTES
hidden: not displayed by browser
file: upload files
autofocus: give focus when page loads
placeholder: inserts value in input field
maxlength: limits number of characters entered in field
Checkbox
document.forms.hero.powers[0].checked = true;
OR
input type='checkbox' value='Flight' name='powers' checked
Radio
form.type[2].checked = true;
OR
input type='radio' name='type' value='Villain' checked
SELECT OPTIONS
Selected attribute shows text initially multiple attribute if more than one option can be selected can access text of options using:
form.city.options[form.city.selectedIndex].text
OR
form.city.value;
TEXTAREA
add text area
textarea name='origin' rows='20' cols='60'>This is a text area...../textarea
OR
form.origin.value = 'This is a textarea text .....';
BUTTON TYPES
reset
button
submit
FORM VALIDATION
The validation of the form help us to avoid corrupted data or prevent malicious inputs
- required field is complete
- email address valid
- validate credit card
- validate numerical data request
- use regex to validate passwords
Is crucial to apply validation to form to minimize a posible vulnerability.
Object-Oriented Programming
The object-oriented programming paradigm is focused on making code more efficient and not repeated during programming when generating classes, in object-oriented programming the functions are called methods.
Encapsulation: inner workings are kept hidden, only essential functionalities exposed can be as a private and public class.
Polymorphism: is process can be used for different objects, can share same method and in another words a object can have differt forms.
Inheritance: inherit properties or methods from existing objects can be reuse it.
Constructor Functions
const dice = {
sides: 6,
roll() {
return Math.floor(this.sides * Math.random() + 1)
}
}
Class Declaration
ES6 introduced the new class declaration syntax that does exactly the same thing as a constructor function, but looks much similar to writing a class in a class-based programming language. Here is the dice example again, using a class declaration:
class Dice {
constructor(sides=6) {
this.sides = sides;
}
roll() {
return Math.floor(this.sides * Math.random() + 1)
}
}
Best practice: names of constructor functions or class declarations are capitalized
declares new instance, using argument for sides:
const blueDice = new Dice(20);
<< Dice { sides: 20 }
all objects have a constructor property that returns constructor function that created it:
blueDice.constructor
<< [Function: Dice]
Static Methods
The static keyword can be used in class declarations to create a static method. These are sometimes called class methods in other programming languages. A static method is called by the class directly rather than by instances of the class
class Dice {
constructor(sides=6) {
this.sides = sides;
}
roll() {
return Math.floor(this.sides * Math.random() + 1)
}
static description() {
return 'A way of choosing random numbers'
}
}
Prototypal Inheritance
JavaScript uses a prototypal inheritance model. This means that every class has a prototype property that is shared by every instance of the class. So any properties or methods of a class’s prototype can be accessed by every object instantiated by that class.
class Turtle {
constructor(name) {
this.name = name;
this.weapon = 'hands';
}
sayHi() {
return `Hi dude, my name is ${this.name}`;
}
attack(){
return `Feel the power of my ${this.weapon}!`;
}
}
Private and Public Methods
objects methods public by default
seen if queried, example dog.animal
changed by assignment, example dog.animal= 2;
class Turtle {
constructor(name,color) {
this.name = name;
let _color = color;
this.setColor = color => { return _color = color; }
this.getColor = () => _color;
}
}
Private method you can use _method
- Imposible to access outside of the class
- Can use to store valuable data or process
- Need to use getter and setter
- you can control what can value accepted
Inheritance
The examples we’ve seen so far have all demonstrated inheritance by inheriting properties and methods from the prototype. But the prototype is just another object, so it also has its own prototype, which in turn has its own prototype... and so on, creating a chain of inheritance.
Prototype chain
Object.getPrototypeOf(raph)
<< Turtle {}
example of inherance
class Turtle {
constructor(name) {
this.name = name;
}
sayHi() {
return `Hi dude, my name is ${this.name}`;
}
swim() {
return `${this.name} paddles in the water`;
}
}
Polymorphism
Methods can be overridden for specific implementation example of that: number.toString() - returns number as a string array.toString() - returns array items as series of strings
[1,2,3].toString()
<< '1,2,3'
Adding Methods to Built-in Objects
It is possible to add more methods to the prototype of JavaScript’s built-in objects — such as Number, String, and Array.
Number.prototype.isEven = function() {
return this%2 === 0;
}
Number.prototype.isOdd = function() {
return this%2 === 1;
}
Proterty ATTS/DESC
value - value of property, default undefined
enumerable - show up if displayed, default false
writable - can be changed or not, default false
configurable - can delete or change, default is false
Object.getOwnPropertyDescriptor(me,'name');
<< { value: 'DAZ',
writable: true,
enumerable: true,
configurable: true }
Getters and Setters
An object property descriptor can have get() and set() methods instead of a value attribute. All objects must have one or the other, they can't have both. The get() and set() methods can be used to control how a property is set using assignment and the value that is returned when a property is queried.
me.age = 21;
me.retirementAge = 65;
Object.defineProperty(me, 'yearsToRetirement',{
get() {
if(this.age > this.retirementAge) { return 0; }
else { return this.retirementAge - this.age; }
},
set(value) {
this.age = this.retirementAge - value;
return value;
}
});
Creating Objects from Other Objects
Object literal:
const Human = {
arms: 2,
legs: 2,
walk() { console.log('Walking'); }
}
Use as prototype, acts as superclass, create instance by:
const lois = Object.create(Human);
Extra properties can be added to instance:
lois.name = 'Lois Lane';
<< 'Lois Lane'
lois.job = 'Reporter';
<< 'Reporter'
const Superhuman = Object.create(Human);
Superhuman.change = function() {
return `${this.realName} goes into a phone box and comes out as ${this.name}!`;
};
Superhuman.name = 'Name Needed';
<< 'Name Needed'
Superhuman.realName = 'Real Name Needed';
<< 'Real Name Needed'
now use new object to create others:
const superman = Object.create(Superhuman);
superman.name = 'Superman';
superman.realName = 'Clark Kent';
superman.change()
Mixins
A mixin is a way of adding properties and methods of some objects to another object without using inheritance. It allows more complex objects to be created by ‘mixing’ basic objects together.
const a = {};
const b = { name: 'JavaScript' };
Object.assign(a,b);
<< { name: 'JavaScript' }
a.name
<< 'JavaScript'
Modern JavaScript Development
In the development enviroment we have the libraries that are code that provides several methods to achive common tasks
JavaScript Way:
para.classList.add('important');
const newPara = document.createElement('p');
newPara.textContent = 'Another Paragraph';
para.appendChild(newPara);
jQuery library
$(para).addClass('important').append('Another Paragraph
');
jQuery Lirbary
- Most popular JavaScript library
- IE functionality
- jQuery addClass()
- you need to downloaded
Advantage of use libraries, the website can be scalable, optimized, tested, battle-testted, online documentation and support
Disadvantage if the library have a bulnerability your website have the vulnerability too
Modular JS
self-contained piece of code that can be used in other files/modules
- Module has own global scope
- All code in modules always in strict mode
- Module has own global scope
- Top level of module is undefined
- can’t use html style comments in modules
example
export const PI = 3.1415926;
saved in module and imported
import { PI } from './pi.js';
MVC frameworks
Aurelia - modern framework uses ES6 lets you write dynamic web apps while keeping implementation in background
Angular - powerful framework created by Google makes creating dynamic web apps easier, extending HTML language using custom ng- atts
Ember - framework to make large web apps easier, uses common conventions that avoids need for lots of setup code
Two camps for inputting code:
Hello {{ name }}
Hello <%= name %>
React- REACT created by Facebook and VUE.js both use virtual DOM use components react uses language called JSX - HTML and JS mixed vue.js uses HTML like templates that contain logic/directives/js objects
YARN - popular alternative to npm, installs faster packages.
NPM - node package manager, allow JavaScript to be shared tools and functionalities
CDNs - contact delivery networks, deliver web resources (like js, css, images) to user
Reference
Forms: https://www.sitepoint.com/premium/books/javascript-novice-to-ninja-2nd-edition/read/8/ Object-Oriented Programming: https://www.sitepoint.com/premium/books/javascript-novice-to-ninja-2nd-edition/read/12/k01nwva7/Contact me
📧Email me at iodaniel@byui.edu
- Lesson 01: Notes
- Lesson 02:
- Lesson 03:
- Lesson 04:
- Lesson 05:
- Lesson 06:
- Lesson 07:
- Lesson 08:
- Lesson 09:
- Lesson 10:
- Lesson 11: