JavaScript Lecture 6 Rachel A Ober rober@ccs.neu.edu

Preview:

Citation preview

JavaScript

Lecture 6

Rachel A Ober

rober@ccs.neu.edu

Using Object in JavaScript

JavaScript is an OOP language. You can use your OO skills to access

different properties of your objects. You can also use built in methods and your

own methods.

Accessing Properties of an Object

If you wanted to get the length of a String object, you can do something like this var name = “Rachel” document.write(name.length)

Which will print… 6

To the document.

Using Methods of an Object

You can also use the methods of an object. Like our example before, we can do

something like this: var name = “Rachel” document.write(name.bold())

Which will print: Rachel

Some Object in JavaScript

String Date Array Boolean Math Events HTML DOM

Manipulating HTML with JavaScript

We can get information about the current document by accessing the HTML element and using it like an object.

For instance, if we have a table with id “table1”, we could access it like this: var table1 = document.getElementById(“table1”)

If we wanted to find out the border of the table, we can write: document.write(table1.border)

Let’s try it!

Manipulating HTML with JavaScript

We can also actively manipulate HTML as well. Take our previous example, this time we want to

have it’s original border to be 1 and we want to change it to 10. Let’s use a function to change the border when we click a button. function changeBorderSize() { document.getElementById(“table1”).border="10 }

Let's try it!

Form Validation

With JavaScript, we can look at the elements on the page after someone has filled in a form and can make sure they are putting in the correct value after they have clicked the button and before the form is submitted.

Suppose we want to check that the user inputted an integer value within the constraints.

Validate Form Field How do we make sure someone entered an integer value

between 1-7? var day_of_week = document.getElementByID(“day”).value if((isNaN(day_of_week)||day_of_week<1||day_of_week>7) {

alert(“Not within range!”) return false

} else {

alert(“Form valid!”) return true

} Let's try it!

Lab #5: Manipulating HTML and Form Validation http://cpu.rachelober.com/lab5 Objective:

Use what we've learned to change elements in the HTML document.

Use what we've learned to validate forms.