Whats the difference between onclick and onsubmit?

It’s not like I haven’t googled it… But still I couldn’t understand when onsubmit is used and when onclick is used?

They’re two completely separate events.

onclick events fire when the user uses the mouse to click on something.

onsubmit events fire when a form is submitted. The origin of this event can sometimes be traced back to an onclick (like clicking the “submit” button) but it can also come from a keyboard event (like pressing enter).

This implies that using onclick on a submit button on a form might miss some cases that an onsubmit on the form would catch.

There are many other kinds of events such as: onload for loading resources such as scripts or images and onkeydown for detecting key presses on the keyboard.

OnSubmit is used on a form, and indicates that the information is to be submitted to the server at this point unless you return false.

OnClick is used on anything, and indicates that it was clicked, offering no other context to the intention of the event at all.

Onclick is the event where a control/object/pretty much anything, is clicked on.
Onsubmit is the event where a form is submitted.

For example, lets say you have a registration form.

You can have the OnClick event of the “Submit” button to bring up an alert that says “Are you sure these details are correct?”, and clicking “Ok” there can trigger the OnSubmit event, which would submit the form data to wherever you want it to go.

Read More:   Convert non-ASCII characters (umlauts, accents...) to their closest ASCII equivalent (for slug creation)

In react as an example, onClick works on every element and it doesn’t capture the full form event like “required”.

     <form >
          <input type="text" placeholder="Enter Name" required />
          <button type="submit" onClick={myHandler} > Submit</button>
      </form>

In the case above, myHandler will execute without regarding the “required” property.

onSubmit, on the other hand, can capture all form events, for example, “required”, but has to be applied to the form element itself.

      <form onSubmit={myHandler}>
          <input type="text" placeholder="Enter Name" required />
          <button type="submit"> Submit</button>
      </form>

Now, the required property works fine.

onsubmit reference to form element and this event occurs when the form is submitted.

http://reference.sitepoint.com/html/event-attributes/onsubmit

onclick reference to elements such as div, li etc, this event occurs when user clicks the element that attribute click is applied to.

http://www.sitepoint.com/web-foundations/onclick-html-attribute/


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts