Sunteți pe pagina 1din 10

JavaScript Basics

The HTML <script> tag is used to insert a JavaScript into an HTML page.

1- How to Put a JavaScript into an HTML Page

Example 1

<html>
<body>
<script type="text/javascript">
document.write("Hello World!");
</script>
</body>
</html>

The code above will produce this output on an HTML page:

Hello World!

Example Explained

To insert a JavaScript into an HTML page, we use the <script> tag. Inside the <script> tag we
use the type attribute to define the scripting language. So, the <script type="text/javascript"> and
</script> tells where the JavaScript starts and ends. The word document.write is a standard
JavaScript command for writing output to a page. By entering the document.write command
between the <script> and </script> tags, the browser will recognize it as a JavaScript command
and execute the code line. In this case the browser will write Hello World! to the page:

JavaScript Code

JavaScript code (or just JavaScript) is a sequence of JavaScript statements. Each statement is
executed by the browser in the sequence they are written. This example will write a heading and
two paragraphs to a web page:

Example 2

<script type="text/javascript">
document.write("<h1>This is a header</h1>");
document.write("<p>This is a paragraph</p>");
document.write("<p>This is another paragraph</p>");
</script>
2- Using Alert Box

<html>
<head>
<title>Printing Multiple Lines in a Dialog Box</title>
<script type = "text/javascript">
window.alert( "Welcome to\nJavaScript\nProgramming!" );
</script>
</head>
<body>
<p>Click Refresh (or Reload) to run this script again.</p>
</body>
</html>

3- Using Prompt Box

<html>
<head>
<title>Using Prompt and Alert Boxes</title>
<script type = "text/javascript">
var name; // string entered by the user
name = window.prompt( "Please enter your name" );
document.writeln( "<h1>Hello " + name + ", welcome to JavaScript programming!</h1>" );
</script>
</head>
<body>
<p>Click Refresh (or Reload) to run this script again.</p>
</body>
</html>

Task 1:

Input two integers from user and display the sum of these values on the page.
4- Using Loops with Prompt Box
This program asks user to enter marks of 10 students and then calculates the average marks.

<html>
<head>
<title>Class Average Program</title>
<script type = "text/javascript">
var total; // sum of grades
var gradeCounter; // number of grades entered
var grade; // grade typed by user (as a string)
var gradeValue; // grade value (converted to intetger)
var average; // average of all grades

// Initialization Phase
total = 0; // clear total
gradeCounter = 1; // prepare to loop
// Processing Phase
while ( gradeCounter <= 10 ) // loop 10 times
{
// prompt for input and read grade from user
grade = window.prompt( "Enter integer grade:", "0" );
// convert grade from a String to an integer
gradeValue = parseInt( grade );
// add gradeValue to total
total = total + gradeValue;
// add 1 to gradeCounter
gradeCounter = gradeCounter + 1;
}
// Termination Phase
average = total / 10; // calculate the average
// display average of exam grades
document.writeln("<h1>Class average is " + average + "</h1>" );
</script>
</head>
<body>
<p>Click Refresh (or Reload) to run the script again</p>
</body>
</html>
Task 2:

Write a script that displays woman when user inputs 1 and displays man when user inputs 2.

Task 3:

Write a script that asks user to input 3 numbers and then displays all the three entered number on
the page and also displays that which of these numbers is maximum (largest).

Task 4:

Write a script that asks user to input 5 pass or fail students and then shows total number of pass
students and total number of fail students. For pass user will input 1 and for fail user will input 0.

3 Different ways to access HTML elements in Javascript

You can access any HTML element from JavaScript using following three ways:

1. myForm["firstName"].value

(where myForm is the name (id) of the <form> tag, and “firstName” is the name of HTML like
textfield, radiobutton or checkbox etc. Your textfield etc must be defined inside the <form> tag)

2. myForm.firstName.value

(where myForm is the name (id) of the <form> tag, and “firstName” is the name of HTML like
textfield, radiobutton or checkbox etc. Your textfield etc must be defined inside the <form> tag)

3. document.getElementById(“firstName”).value

(Here you can access any element directly through its name e.g. firstName)
5- Confirm Password Check

<html>
<head>
<title> Illustrate password checking </title>
<script type = "text/javascript">
function chkPasswords() {
var init = document.getElementById("initial");
var sec = document.getElementById("second");
if (init.value == "") {
alert("You did not enter a password \n" + "Please enter one now");
init.focus();
return false;
}
if (init.value != sec.value) {
alert("The two passwords you entered are not the same \n" + "Please re-enter both now");
init.focus();
return false;
} else
return true;
}
</script>
</head>
<body>
<h3> Password Input </h3>
<form id = "myForm" action = "" onsubmit = "chkPasswords()">
<p>
<input type = "password" id = "initial" size = "10" />
</label>
<br /><br />
<label> Verify password
<input type = "password" id = "second" size = "10" />
</label>
<br /><br />
<input type = "reset" name = "reset" />
<input type = "submit" name = "submit" />
</p>
</form>
</body>
</html>
6- JavaScript Form Validation

JavaScript can be used to validate input data in HTML forms before sending off the content to a
server.

Form data that typically are checked by a JavaScript could be the user has left required fields
empty? The user has not entered a valid e-mail address? The user has entered text in a numeric
field?

Consider the following form. We will validate all the fields through JavaScript. The complete
code is written below:
<html>
<head>
<title>Registration</title>
<script>
function validate()
{
var flag;
//var alphaExp = /^[a-zA-Z]+$/;
//if(!myform.user.value.match(alphaExp))
//{
// alert("Please enter a valid name");
// myform.user.focus();
// return false;
//}
// Validating First Name
if(myform.firstname.value =="" )
{
alert("Please enter your first name");
myform.firstname.focus();
return false;
}
// Validating Last Name
if(myform.lastname.value=="")
{
alert("Please enter your last name");
myform.lastname.focus();
return false;
}
// validating Radio buttons. Select only one radio.
flag = false;
for(i=0; i<myform.gender.length; i++)
if(myform.gender[i].checked)
flag = true;
if(!flag)
{
alert("Please select your gender");
return false;
}
// validating Dropdown list.
if(myform.subject.selectedIndex == 0)
{
alert("Please select option from the list");
return false;
}
// validating checkboxes. At least one must be selected
if(!myform.chk1.checked)
if(!myform.chk2.checked)
if(!myform.chk2.checked)
{
alert("Please select at least one Programming Language");
return false;
}

return true;
}
</script>
</head>

<body>
<h1>Feedback Form </h1>
Please complete the following form to register your feedback:<br>
<form id=myform method="get" action="" onSubmit="return validate();">
<table width=40%>
<tr>
<td>
First Name:
</td>
<td>
<input type="text" name="firstname" id="firstname">
</td>
</tr>

<tr>
<td>
Last Name:
</td>
<td>
<input type=text name="lastname" id="lastname">
</td>
</tr>

<tr>
<td>
Gender:
</td>
<td>
<input type=radio name=gender value="male"> Male <br>
<input type=radio name=gender value="female"> Female
<br>
</td>
</tr>

<tr>
<td>
Select your favourite Subject:</td>
<td>
<select id="subject">
<option value="" selected>Select Subject</option>
<option value="wt">Web Technologies-1</option>
<option value="os">Operating System</option>
<option value="se">Software Engineering</option>
<option value="dc">Data Communication</option>
</select>
</td>
</tr>

<tr>
<td> Choose Programming Languages that you like:
<span style="font-size:12px"></span>
</td>
<td><br>
<input type=checkbox name="chk1" value="c">
C++<br>
<input type=checkbox name="chk2" value="j">
Java<br>
<input type=checkbox name="chk3" value="p">
PHP<br>
</td>
</tr>

<tr>
<td>
<br>
</td>
<td>
<input type=submit value="Register now">
</td>
</tr>

</table>
</body>

</form>
</html>
Task 5:

Step 1: Draw the following form.

Step 2: Validate the form fields through JavaScript.

Step 3: Validation should be performed on the password and confirm password fields. For this
purpose create a separate function confirmPassword() that checks whether these two fields
contain same value or not.

S-ar putea să vă placă și