Event handling in web development allows JavaScript to respond to user actions and system
events. onClick and onSubmit are key events, with onClick triggering when a user clicks on
an element (like a button) and onSubmit triggering when a form is submitted.
Illustrative Examples:
1. onClick Example:
Code
<button onclick="alert('Button clicked!')">Click Me</button>
Explanation:
When the user clicks the button, the alert() function displays a message box with
"Button clicked!".
The onclick event attribute is directly attached to the <button> element.
2. onSubmit Example:
Code
<form onsubmit="submitForm(event)">
<input type="text" name="name" placeholder="Enter your name">
<button type="submit">Submit</button>
</form>
<script>
function submitForm(event) {
event.preventDefault(); // Prevent the default form submission
const name = document.querySelector('input[name="name"]').value;
alert(`You submitted with the name: ${name}`);
// Add your logic here to process the form data
}
</script>
Explanation:
The onsubmit event is attached to the <form> element.
When the form is submitted (by clicking the submit button or pressing Enter),
the submitForm() function is called.
event.preventDefault() prevents the browser's default form submission behavior,
allowing you to handle the submission with JavaScript.
The code retrieves the value of the "name" input field and displays it in an alert box.
You can replace the alert() with your own logic, such as sending the form data to a
server or updating a database.