120 likes | 429 Views
JavaScript Validation. Making Decisions. IF statements can be used to make logical decisions IF statements require a CONDITION that is evaluated to TRUE or FALSE Conditions use conditional operators: >, <, >=, <=, ==, != intGrade = prompt('What is your grade?'); if ( intGrade <= 60) {
E N D
Making Decisions • IF statements can be used to make logical decisions • IF statements require a CONDITION that is evaluated to TRUE or FALSE • Conditions use conditional operators: >, <, >=, <=, ==, != intGrade = prompt('What is your grade?'); if (intGrade <= 60) { alert('You fail!'); } else { alert('You pass.'); }
JavaScript and Forms • HTML Forms have a special usage in JavaScript IF you’ve given the elements a NAME attribute. • You could always just use the ID and getElementById() • To access a form with JavaScript, use: document.forms['FormName'] • To access an element inside that form, use: document.forms['FormName']['ElementName'] • There are some specialized ways (such as dropdown boxes, you should be able to find those and use them)
How Form Validation May Look window.onload = startScripts; function startScripts() { varfrm = document.forms['contactForm']; frm.setAttribute('onsubmit', 'return validateForm()'); } function validateForm() { varfrm = document.forms['contactForm']; if (frm['firstName'].value == '') { alert('First Name cannot be blank! '); return false; } }
Form Validation Possibilities • Validation can be rather lengthy when doing things such as email addresses or phone numbers (think about it!) • You will PROBABLY utilize someone else’s script when doing validation UNLESS • You have a specialized thing to validate • You cannot find a script that does exactly what you want • You loooooove JavaScript • We will utilize the script found here: http://www.javascript-coder.com/html-form/javascript-form-validation.phtml#download