-1

Look at the two following examples:

function myFunction() {
  alert("The form was submitted");
}
 <form onsubmit="myFunction()">
  Enter name: <input type="text">
  <input type="submit">
</form> 

function myFunction() {
  alert("The form was submitted");
}
 <div onchange="myFunction()">
  Enter name: <input type="text">
</div> 

As you can see, the main difference between the two code snippets is the submit button which exist in the first snippet but omitted in the second one.

It can't be the only reason (submission button) to prefer the use of 'onsubmit' over the 'onchange' event. I mean, form element provides native form validation features which make it very powerfull tool for handling user input. Is there any reason at all to prefer the use of div (with onchange attr.) element over the form (with onsubmit attr.) element.

A few real world use cases will help me to build a solid and an intuitive understanding.

altgov3en
  • 1,100
  • 2
  • 18
  • 33
  • A `form` can have hundreds or thousands of `input` elements, each of them dispatching a `change` event when the user changes its value. Isn't it obvious what is the difference then? Also please note that using inline event listeners like `onchange` and `onsubmit` is generally considered bad practice. Use `element.addEventListener(event, () => {})` in your Javascript code instead. – connexo May 19 '19 at 16:33
  • @connexo, can you tell why the inline event listeners are considered bad practice? – altgov3en May 20 '19 at 06:27
  • [This is](https://stackoverflow.com/questions/11737873/why-are-inline-event-handler-attributes-a-bad-idea-in-modern-semantic-html) what I found on the subject – altgov3en May 20 '19 at 06:34

1 Answers1

1

The onchange event occurs when the value of an element has been changed. The onSubmit event occurs when you try to submit a form

Subin
  • 376
  • 1
  • 4
  • 16