/    /  JavaScript Form Event

JavaScript Form Event

 

Javascript form control receives or loses focus or when the user changes a form control value such: typing text in text input fields, and select an option in a select box, etc. Here are some most important form events and their event handler.

 

Focus Event (onfocus):

The onfocus javascript event handler is provided to handle this event. The below example will highlight the background of text input in green color when it receives the focus.

 

EXAMPLE:

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript Handling the Focus Event </title>
</head>
<body>
<script>
function highlightInput(elm){
elm.style.background = "lightgreen";
} 
</script>
<input type="text" onfocus="highlightInput(this)">
<button type="button">Button</button>
</body>
</html>

 

OUTPUT:

 

JavaScript Form Event

 

Blur Event (onblur):

This javascript event occurs when the user takes the focus away from a form element.

 

EXAMPLE:

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript Handling the Blur Event </title>
</head>
<body>
<input type="text" onblur="alert('Text input loses focus!')">
<button type="button">Submit</button>
<p><strong>Note:</strong> First click inside the text input box then click outside to see how it works.</p>
</body>
</html>

 

OUTPUT:

 

JavaScript Form Event

 

Change Event (onchange):

The value of a form element is changed.

 

EXAMPLE:

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript OnChange Event</title>
</head>
<body>
<select onchange="alert('You have changed the selection!');">
<option>Select</option>
<option>OnePlus</option>
<option>Samsung</option>
</select>
<p><strong>Note:</strong> Select any option in select box to see how it works.</p>
</body>
</html>

 

OUTPUT:

 

JavaScript Form Event