Skip to main content

Form Events in JavaScript (Live Playground)

In this tutorial, we'll explore how to work with form events in JavaScript to create more interactive and user-friendly web forms. We'll cover common form events such as submit, change, and focus.

Common form events

Here are some common form events you might encounter when working with JavaScript:

  • submit: Triggered when a user submits a form.
  • change: Triggered when the value of an input element changes.
  • focus: Triggered when an input element receives focus.

Handling form events

To handle form events in JavaScript, you can use the addEventListener() method. Here's an example of how to handle the submit event:

<!DOCTYPE html>
<html>
<head>
<title>Form Events Example</title>
</head>
<body>
<form id="myForm">
<input type="text" placeholder="Your name" />
<input type="submit" value="Submit" />
</form>

<script>
// Get a reference to the form element
var form = document.getElementById('myForm');

// Function to handle the submit event
function handleSubmit(event) {
event.preventDefault();
console.log('Form submitted!');
}

// Add a submit event listener to the form
form.addEventListener('submit', handleSubmit);
</script>
</body>
</html>

In this example, we define a handleSubmit() function that prevents the default form submission behavior and displays a log message instead. We then use the addEventListener() method to register the handleSubmit() function as a callback for the submit event on the form element.

Live Playground, Try it Yourself

Example: Detecting changes in an input field

Now let's create an example where we detect changes in an input field:

<!DOCTYPE html>
<html>
<head>
<title>Input Change Detection Example</title>
</head>
<body>
<input type="text" id="myInput" placeholder="Type something..." />

<script>
// Get a reference to the input element
var input = document.getElementById('myInput');

// Function to handle the change event
function handleChange() {
console.log('Input value changed!');
}

// Add a change event listener to the input
input.addEventListener('change', handleChange);
</script>
</body>
</html>

In this example, we define a handleChange() function that displays a log message when the input value changes. We then use the addEventListener() method to register the handleChange() function as a callback for the change event on the input element.

Live Playground, Try it Yourself