Jeremy Troy Suchanski                                   

Web Frontend Development II

Gary James                                                                  

May 4, 2022

L06 Readings Notes

Ch8: Forms (Notes)

<!doctype html>

<html lang='en'>

<head>

    <meta charset='utf-8'>

    <title>Search</title>

</head>

<body>

    <form name='search' action='/search'>

        <input name='searchInput'>

        <button type='submit'>Search</button>

    </form>

<script src='main.js'></script>

</body>

</html>

Accessing Form Elements

Form Properties and Methods

Form Events

Submitting a Form

Code Example:

const form = document.forms['search'];

form.addEventListener ('submit'searchfalse);

function search() {

    alert(' Form Submitted');

    event.preventDefault(); }

Retrieving and Changing Values From a Form

function search(event) {

    alert(`You Searched for: ${input.value}`);

    event.preventDefault();

  }

input.addEventListener('focus'function(){

  if (input.value==='Search Here') {

      input.value = ''  }

}, false);

input.addEventListener('blur'function(){

  if(input.value === '') {

      input.value = 'Search Here';

  } }, false);

<input type='text' name='search-box' placeholder='Search Here'>

<input>: fields, including text, passwords, check boxes, radio buttons, and file uploads

<select>: menus for drop-down lists of options

<textarea>: elements for longer text entry

<button>: elements for submitting and resetting forms

Code Example:  Once the object is created, normally it would be returned by the function & then used elsewhere in the rest of the program. Instead, since this is just a demo, we convert the object into a JSON string using JSON.stringify() method & then display it in an alert dialog.

 function makeHero(event) {

  event.preventDefault(); // prevent the form from being submitted

  const hero = {}; // create an empty object

  hero.name = form.heroName.value// create a name property based on the input field's value

  alert(JSON.stringify(hero)); // convert object to JSON string and display in alert dialog

  return hero; }

value attribute: can set the initial value of this field in HTML. Code Example:

<label for='donation-amount'>Enter amount to donate: 

  <input type='text' id ='donation-amount' name='donationAmount' value='10'>

</label>

  1. Password Input Fields (input type='password'): used to enter passwords or secret information. The characters are concealed as they are entered so they’re unable to be read on the screen. Code Example:

<label for='realName'>Real Name:

  <input type='password' name='realName' id='realName'></label>

JavaScript File:

hero.realName = form.realName.value;

  1. Checkbox Input Fields (type='checkbox'): used to select different options that can be checked (true) or left unchecked (false). The user can select more than one checkbox from a list. 

checked property: a property of checkbox objects that tells us if it has been checked or not with values of true or false.

value property: used to set the name of the value of the checkbox choice if checked.

Code Example:

<p>Super Powers:</p>

<label for='flight'>Flight:

    <input type='checkbox' id='flight' value='Flight' name='powers'>

</label>

<label for='strength'>Super Strength:

    <input type='checkbox' id='strength' value='Strength' name='powers'>

</label>

<label for='speed'>Super Speed:

    <input type='checkbox' id='speed' value='Super Speed' name='powers'>

</label>

<label for='energy'>Energy Blasts:

    <input type='checkbox' id='energy' value='Energy Blasts' name='powers'>

    </label>

<label for='telekinesis'>Telekinesis:

    <input type='checkbox' id='telekinesis' value='Telekinesis' name='powers'>

</label>

(above all the checkbox elements have the same 'name' property of 'powers', so form.powers; will access them as an HTML collection)

for loop: can be used to iterate over the collection to see if each checkbox was checked. Code Example

hero.powers = [];

for (let i=0i < form.powers.length; i++) {

    if (form.powers[i].checked) {

        hero.powers.push(form.powers[i].value); } }

spread operator (. . .): turn the node list into an array.

filter() method: returns an array containing only the check boxes that were checked.

map() method: replaces each checkbox in the array with its 'value' property.

variable: stores the array. Code Example

hero.powers = [...form.powers].filter(box => box.checked).map(box => box.value);

'checked' property: can set a checkbox to true using JavaScript. Code Example:

document.forms.hero.powers[0].checked = true;

'checked' attribute: in the HTML can initially set checkboxes as checked. 

Code Example:

<input type='checkbox' value='Flight' name='powers' checked>

  1. Radio Button Input Fields (type='radio'): they allow users to check an option as true, but only one option can be selected. Code Example:

'name' attribute of 'category': reused to group radio buttons together ― only one can be checked in a group with the same name attribute. Code Example:

<p>What type of hero are you?</p>

<label for='hero'>Hero:

    <input type='radio' name='category' value='Hero' id='hero'>

</label>

<label for='villain'>Villain:

    <input type='radio' name='category' value='Villain' id='villain'>

</label>

<label for='anti-hero'>Anti-Hero:

    <input type='radio' name='category' value='Antihero' id='anti-hero'>

</label>

name property: can access an HTML collection of all the radio buttons. 

Code Example

form.category

form.category.value: Where value of the radio button that was selected is stored and can be used to assign a category property to an object. Code Example:

hero.category = form.category.value;

'checked' property: returns the boolean values true if selected or false if not.

JavaScript changing checked property: (others change to false) Code Example:

form.type[2].checked = true;

'checked' attribute: in the HTML can initially set radio button as checked.

Code Example:

<input type='radio' name='type' value='Villain' checked>

  1. Hidden Input Fields (type='hidden'): are not displayed by the browser, but have a 'value' attribute that can contain information that is submitted with the form. They are often used to send information such as settings or information that the user has already provided. Note that the information in these fields is in no way secret, as it’s visible in the HTML, so shouldn’t be used for sensitive data. The value of a hidden input field can be changed using JavaScript in the same was as any other input field.
  2. File Input Fields (type='file'): used to upload files, most browsers will provide a browse button or similar that lets users select a file from their file system.
  3. Other Input Types (type='number', type='tel', type='color', type='date', type='email'): There are lots of new input types included in HTML5. As browsers start to support these, they will implement different user-interface elements & validate automatically. If the new input type isn’t supported the browser will just display a normal text input field. New form elements link
  4. Number input fields (type='number'): have optional 'min' and 'max' attributes that can be used to limit the input given. The 'step' attribute is used to specify how much the value changes by each click.
  5. Select Drop-Down List: used to select one or more options from a list of values.

'multiple' attribute: required if more than one option is to be selected. 

Code Example

<label for='City'>Base of Operations:

  <select name='city' id='city'>

      <option value='' selected>Choose a City</option>

      <option value='Metropolis'>Metropolis</option>

      <option value='Gotham City'>Gotham City</option>

      <option value='Keystone City'>Keystone City</option>

      <option value='Coast City'>Coast City</option>

      <option value='Star City'>Star City</option>

  </select>

</label>

'selected' attribute: used to set the initial value in the HTML. If only one item was selected, this will return a reference to that selection; otherwise a collection will be returned containing each selection. Code Example:

form.city;

value property: equal to the 'value' attribute of the <option> tag that was selected. Code Example

hero.city = form.city.value;

selectedIndex property: finds the index of the option that has been selected. This can then be used with index notation to access the actual text of the selected option. Code Example

form.city.options[form.city.selectedIndex].text

  1. Text Areas (<textarea> element): used to enter long pieces of text over multiple lines such as a comment or blog post.

<label for='origin'>Origin Story:

  <textarea id='origin' name='origin' rows='20' cols='60'></textarea>

</label>

'name' attribute: used to access the text area.

value property: used to see what text was entered.

object property: can be added from text area through JavaScript. Code Example:

hero.origin = form.origin.value;

            JavaScript changing text area value in the form: Code Example:

form.origin.value = 'Born as Kal-El on the planet Krypton...';

            text area initial value: set in the HTML by placing the text between the opening and closing tags. Code Example

<textarea name='origin' rows='20' cols='60'>Born as Kal-El on the planet Krypton...</textarea>

validation API: is an optional part of HTML5. (lacks the full support from all browsers at the moment) It works by simply adding relevant attributes to the form fields. Link

required attribute: As you click in another field, the blank name field is highlighted because it’s a required field. Code Example

<input type='text' id='heroName' name='heroName' autofocus placeholder='Your Super Hero Name' maxlength=32 required>

custom form validation: you can create your own custom validation using JavaScript. Code Example

form.addEventListener('submit',validate,false);

function validate(event) {

    const firstLetter = form.heroName.value[0];

    if (firstLetter.toUpperCase() === 'X') {

        event.preventDefault();

        alert('Your name is not allowed to start with X!'); } }

instant feedback: improves the usability of the form. by adding the event listener directly to the input field that will fire when the user presses a key (using the keyup event). The feedback can then be inserted inside the label element of the input field, along with a class of error for more direct feedback. Code Example:

const label = form.querySelector('label');

const error = document.createElement('div');

error.classList.add('error');

error.textContent = '! Your name is not allowed to start with X.';

label.append(error);

function validateInline() {

    const heroName = this.value.toUpperCase();

    if(heroName.startsWith('X')){

    error.style.display = 'block';

    } else {

    error.style.display = 'none';  } }

CSS File:

.error {

    background#f99;

    border#900 1px solid;

    displaynone; }

disabled attribute: adding it to the <input> element disables the button. Code Example

<button type='submit' id='submit' disabled>Submit</button>

using the disabled property of the <button> element with JavaScript: disables the button conditionally. Code Example

function disableSubmit(event) {

  if(event.target.value === ''){

      document.getElementById('submit').disabled = true;

  } else {

      document.getElementById('submit').disabled = false; } }

Using FormData Objects Effectively (Notes)

Using FormData to Parse Forms

document.addEventListener("DOMContentLoaded", () => {

  document.getElementById("myForm").addEventListener("submit"handleForm);

});

Code Example:

function handleForm(ev) {

  ev.preventDefault(); //stop the page reloading

  let myForm = ev.target;

  let fd = new FormData(myForm);

  //add more things that were not in the form

  fd.append("api-key""myApiKey");

  //look at all the contents

  for (let key of fd.keys()) {

    console.log(keyfd.get(key)); }

  //send the request with the formdata

  let url = "http://localhost:3000/";

  let req = new Request(url, {

    body: fd,

    method: "POST" });

  fetch(req)

    .then((res=> res.json())

    .then((data=> {

      console.log("Response from server");

      console.log(data); })

  .catch(console.warn); }

Code Example:

const http = require('http');

const server = http.createServer(function (reqres) {

  req.on('data'function (data) {

    //handle data as it is received... for POST requests

  });

  req.on('end'function () {

    res.setHeader('Content-Type''application/json');

    res.setHeader('Access-Control-Allow-Origin''*');

    res.writeHead(200'OK');

    res.end('{ "data": "just a plain old json reply" }'); }); });

server.listen(3000, (err=> {

  if (err) {

    console.log('bad things');

    return; }

  console.log('listening on port 3000'); });

obj: create an object with a variable name

obj[key]: create a property on the object with the same name as the key & set value to formData.get(key)

JSON.stringify: converts json object to a string.

return: the object is returned

Code Example:

function convertFD2JSON(formData) {

  let obj = {};

  for (let key of formData.keys()) {

    obj[key= formData.get(key); }

  return JSON.stringify(obj); }

Code Example:

Variable: json becomes variable for the data converted to a json file

let json = await convertFD2JSON(fd);

Header object: use to tell the server I am sending you some json data

let h = new Headers();

h.append("Content-type""application/json");

headers: set equal to the Header object created

let req = new Request(url, {

  headers: h,

  body: json,

  method: 'POST', });

 

iterator: considered to be asynchronous so add async to handleForm function 

async function handleForm(ev) {

Json data: put it inside handleForm function

let req = new Request(url, {

    body: json,

    method: "POST" });

MDN: Client-Side Form Validation (Notes)

Properties made available to above 6 element through the API

  1. validationMessage: Returns a localized message describing the validation constraints that the control doesn't satisfy (if any).
  2. validity: Returns a ValidityState object that contains several properties describing the validity state of the element.

ValidityState object properties: some of the more common ones are #1 patternMismatch #2 tooLong #3 tooShort #4 rangeOverflow #5 rangeUnderflow #6 typeMismatch #7 valid #8 valueMissing

  1. willValidate: Returns true if the element will be validated when the form is submitted; false otherwise.

Methods made available to above 6 element through the API

  1. checkValidity(): Returns true if the element's value has no validity problems; false otherwise. If the element is invalid, this method also fires an invalid event on the element.
  2. reportValidity(): Reports invalid field(s) using events. Useful in combination with preventDefault() in an onSubmit event handler.
  3. setCustomValidity(message): Adds a custom error message to the element; if you set a custom error message, the element is considered to be invalid, and the specified error is displayed.