Java Script Advance
Java Script Advance
JavaScript Forms
HTML form validation can be done by JavaScript.
If a form field (fname) is empty, this function alerts a message, and returns false, to
prevent the form from being submitted:
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
The function can be called when the
form is submitted:
<form name="myForm" action="/action_page.php" onsubmit="re
turn validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
The HTML DOM (Document Object
Model)
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects:
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
HTML DOM properties are values (of HTML Elements) that you can set or
change.
Finding HTML Elements
Method Description
</body>
Adding Events Handlers
Method Description
<script>
document.getElementById("myImage").setAttri
bute(“width”,”200”);
</script>
</body>
</html>
JavaScript HTML DOM - Changing
CSS
html>
<body>
<script>
document.getElementById("p2").innerHTML = “Hello
pakistan";
</script>
</body>
</html>
Exercise
1. Use the HTML DOM to hide the <p> element.
2. Use the HTML DOM to change the text size of <p> to 40 pixels.
3. Write a JavaScript function to add rows to a table.
4. Write a JavaScript program to remove items from a dropdown list.
5. Write a JavaScript program to count and display the items of a dropdown list,
in an alert window.
JavaScript HTML DOM Events
Examples of HTML events:
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}
</script>
</body>
</html>
The onload and onunload Events
<!DOCTYPE html>
<html> <body>
<head>
<script> Enter your name: <input type="text" id="fname"
onchange="myFunction()">
function myFunction() {
<p>When you leave the input field, a function is triggered
var x = document.getElementById("fname");
which transforms the input text to upper case.</p>
x.value = x.value.toUpperCase();
} </body>
</script> </html>
</head>
Mouse Events Keyboard Events Form Events Document/Window Events
The try statement lets you test a block of code for errors.
The finally statement lets you execute code, after try and catch, regardless of the
result.