KEMBAR78
L16 - JavaScript Handling Forms Statements | PDF | Java Script | Control Flow
0% found this document useful (0 votes)
6 views6 pages

L16 - JavaScript Handling Forms Statements

The document provides an overview of handling forms and statements in JavaScript, emphasizing the importance of forms for user input and various methods to access and manipulate form elements. It covers form submission handling, event listeners, and different types of JavaScript statements including declarations, conditionals, loops, and error handling with try-catch-finally. Examples are provided to illustrate the syntax and usage of these concepts.

Uploaded by

wazahatkarim02
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views6 pages

L16 - JavaScript Handling Forms Statements

The document provides an overview of handling forms and statements in JavaScript, emphasizing the importance of forms for user input and various methods to access and manipulate form elements. It covers form submission handling, event listeners, and different types of JavaScript statements including declarations, conditionals, loops, and error handling with try-catch-finally. Examples are provided to illustrate the syntax and usage of these concepts.

Uploaded by

wazahatkarim02
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

JavaScript: Handling Forms & Statements

I. Handling Forms in JavaScript

Forms are essential in web development for gathering user input. JavaScript allows you to
validate, manipulate, and interact with form elements to provide a dynamic user experience.

1. Accessing Form Elements

In JavaScript, you can access form elements in multiple ways, using the document object,
typically through getElementById(), getElementsByName(), getElementsByTagName(),
or querySelector().

Syntax:

let element = document.getElementById('elementID');


let element = document.forms['formName'].elementName;
let element = document.querySelector('form input[name="username"]');

Example:

<form id="userForm">
<input type="text" name="username" id="username">
<input type="password" name="password" id="password">
<input type="submit" value="Submit">
</form>

<script>
let form = document.getElementById('userForm');
let username = form.username.value;
let password = form.password.value;

console.log(username, password); // Logs the values when form is


submitted
</script>

2. Handling Form Submission

You can handle form submission with the onsubmit event. You can use this event to validate
the form, send the form data to a server, or prevent the form from submitting.

Syntax:

<form id="formId" onsubmit="return functionName();">

Example (Simple form validation):

<form id="myForm" onsubmit="return validateForm();">


<input type="text" id="name" name="name">
<input type="submit" value="Submit">
</form>

<script>
function validateForm() {
let name = document.getElementById('name').value;
if (name == "") {
alert("Name must be filled out");
return false; // Prevent form submission if validation fails
}
return true; // Allow form submission if validation passes
}
</script>

3. Event Listeners for Form Input Fields

Instead of using inline event handlers (like onsubmit or onchange), you can use
addEventListener() to attach event listeners for better separation of JavaScript and HTML.

Example (Listening for input changes):

<form id="signupForm">
<input type="text" id="email" name="email" placeholder="Enter email">
<input type="submit" value="Submit">
</form>

<script>
document.getElementById('email').addEventListener('change', function() {
let email = this.value;
console.log("Email Changed:", email);
});
</script>

II. JavaScript Statements

In JavaScript, statements are used to perform operations and define the flow of control in
your program. JavaScript supports several types of statements: expressions, conditionals,
loops, and more.

1. Declaration Statements

• Variable Declaration: Variables can be declared using var, let, or const in


JavaScript.

Syntax:

let x = 10;
const pi = 3.14;
var name = 'John';

2. Conditional Statements

Conditional statements in JavaScript control the flow of execution based on conditions.

• If Statement:

Syntax:

if (condition) {
// Code block if condition is true
}
Example:

let age = 18;


if (age >= 18) {
console.log("You are an adult.");
}

• If-Else Statement:

Syntax:

if (condition) {
// Code block if condition is true
} else {
// Code block if condition is false
}

Example:

let age = 16;


if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}

• Else If Statement:

Syntax:

if (condition1) {
// Code block if condition1 is true
} else if (condition2) {
// Code block if condition2 is true
} else {
// Code block if neither condition is true
}

Example:

let score = 75;


if (score >= 90) {
console.log("Grade A");
} else if (score >= 70) {
console.log("Grade B");
} else {
console.log("Grade C");
}
3. Looping Statements

JavaScript provides several loop structures to iterate over a block of code.

• For Loop:

Syntax:

for (let i = 0; i < length; i++) {


// Code block to be executed
}

Example:

for (let i = 0; i < 5; i++) {


console.log(i); // Logs 0, 1, 2, 3, 4
}

• While Loop:

Syntax:

while (condition) {
// Code block to be executed
}

Example:

let i = 0;
while (i < 5) {
console.log(i); // Logs 0, 1, 2, 3, 4
i++;
}

• Do-While Loop:

Syntax:

do {
// Code block to be executed
} while (condition);

Example:

let i = 0;
do {
console.log(i); // Logs 0, 1, 2, 3, 4
i++;
} while (i < 5);
4. Switch Statement

The switch statement is used to perform different actions based on different conditions. It is
often used as an alternative to multiple if/else statements.

Syntax:

switch (expression) {
case value1:
// Block of code if expression == value1
break;
case value2:
// Block of code if expression == value2
break;
default:
// Block of code if none of the cases match
}

Example:

let day = 2;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Invalid day");
}

5. Break & Continue Statements

• Break: The break statement is used to exit a loop or switch statement prematurely.
• Continue: The continue statement skips the current iteration of a loop and proceeds
with the next iteration.

Example (Break in a loop):

for (let i = 0; i < 10; i++) {


if (i === 5) {
break; // Exits the loop when i equals 5
}
console.log(i);
}
Example (Continue in a loop):

for (let i = 0; i < 10; i++) {


if (i === 5) {
continue; // Skips this iteration when i equals 5
}
console.log(i);
}

6. Try-Catch-Finally Statements

JavaScript uses try, catch, and finally blocks for handling errors.

• Try: The try block contains code that might throw an error.
• Catch: The catch block contains code to handle any errors that are thrown.
• Finally: The finally block contains code that is executed regardless of whether an
error occurred.

Example:

try {
let result = 10 / 0;
if (result === Infinity) throw "Division by zero is not allowed";
} catch (error) {
console.log("Error:", error);
} finally {
console.log("Execution completed.");
}

You might also like