MM211 Lecture 12 - JS2
MM211 Lecture 12 - JS2
Lecture 12
JavaScript Part 2
Zoubeir Aungnoo
Learning Outcomes
■ JS with Forms
■ JS Variables
■ querySelector() vs getElementById()
■ Order matters
■ Events revisited
■ Anonymous functions
■ Build a simple search
■ Processing forms
Forms
■ It is common to use JS with forms, esp to validate form
info before submitting to web server
■ onSubmit event
■ false stops the form submission
■ this keyword refers to the current form being submitted
– Validate function accepts an argument, which is the
form object
■ hellojs1.html
Variables
■ In JS we use let to declare variables, without needing to indicate
types
■ is a global variable in JS
■ is a function we can use to select a node in
the DOM
■ After we select the element with the ID
■ We get the text inside the input
■ Then add it to our alert
querySelector vs
getElementById
.querySelector() .getElementById()
Select an element based on a can only select an element by its
CSS selector ID
Specify: ID, class, or any other Limited to only select element by
type of selector its specified id
Can use a more elaborate rule to
select elements
e.g. the first element in a list
e.g. the element which has focus
■ CSS Selectors:
https://www.w3schools.com/cssref/css_selectors.asp
Order matters
■ Consider hellojs3.html
■ Solution:
– Move <script> after the form
– After form rendered we add the event listeners
Events
■ We can listen to events in JavaScript, which occur when
something happens on the page.
■ In previous example, hellojs2.html, the onsubmit event
was added as an attribute
■ In hellojs3.html it didn’t work because of the ordering
■ JS Events:
– https://www.w3schools.com/js/js_events.asp
– https://www.w3schools.com/jsref/dom_obj_event.asp
Anonymous functions
■ An anonymous function is a function without a name.
■ The following shows how to define an anonymous function:
■ process1.html
Process Forms: radio
button
■ Using querySelector() it’s possible to determine which
radio button has been selected
■ Then using programming construct like a switch
statement the choice can be processed
– process1.html