mhpreiman
4/11/2018 - 6:39 PM

forms

Notes

  • Prefer submit over click:   $('form').submit(function() { return validate(fields); })
  • To stop form submission in Firefox, return false inside the validation function isn't enough.
    To do that, add the return keyword before the function call, eg   return validation();
  • Difference between event.preventDefault and return false


Accessing elements

document.forms.length               //number of forms

document.forms[0].elements[0]       //first element of first form

document.forms["myform"]["email"]   //element with name=email in form with name='myform'      same as:
document.myform.email       

document.querySelector("input[type='email']")   //<input type='email'>


Options properties

el = document.getElementById("myselection")<select>

  `el.selectedIndex`     **index** of the selected <option>  (same as `el.OPTIONS.selectedIndex` and `el.OPTIONS[EL.selectedIndex].index`)  
  `el.options`     all (list of) <option> **objectS**  
  `el[el.selectedIndex]`     selected <option> **object**  (same as `el.OPTIONS[el.selectedIndex]`)  
  `el.value`     **value** property of the **selected** <option>  (same as `el.options[selectBox.selectedIndex].value`)  
  `el.options[el.selectedIndex].text`     innerHTML (**text**) of **selected** <option>  

## Validation ### Simple e-mail ``` email = function () { var meil = document.myform.email;

var atPos = meil.indexOf("@"); var dotPos = meil.lastIndexOf("."); if (atPos < 1 || dotPos-atPos < 2) { return false; } }

if (email() == false) { console.log("Sisestatud meil ei tööta"); }


<br>
## Helpers
### Clear field once (only on first focus)

var clearValue = { firstClear : true,
clear : function(input){
if (this.firstClear){
input.value = "";
this.firstClear = false; } } };

```html
<input onfocus="clearValue.clear(this)" value="foobar">


Automation

Create a long list of (numeric) options

function createOptions(selectionID,first,last,defaultOption) {
    var option;
    var selected;
    var parent = document.getElementById(selectionID);

    for (option=first; option<=last; option++) {
        selected = (option == defaultOption) ? 'selected' : '';
        parent.insertAdjacentHTML("beforeend", "<option value='"+option+"'"+selected+">"+option+"</option>");
      }
}

createOptions('selectYear',1950,2020,1999);   //select id,start,end,default
<select id="selectYear" name="selectYear"></select>