Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use the input's onclick or the form's onsubmit event to validate form fields using JavaScript?

I have a simple form with fields that I am trying to validate using JavaScript. In the form I have an input type of submit.

For validation, should I call the validation function for onclick event on the input or onsubmit of the form? Is there any implication of choosing one over the other one?

like image 925
Aditya Shukla Avatar asked Dec 25 '10 01:12

Aditya Shukla


People also ask

Should I use Onsubmit or onclick?

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.

What is the use of Onsubmit event in JavaScript?

The onsubmit event is an event that occurs when you try to submit a form. You can put your form validation against this event type. The following example shows how to use onsubmit. Here we are calling a validate() function before submitting a form data to the web server.

What event should be used to finish work with form?

The submit event occurs when a form is submitted. This event can only be used on <form> elements. The submit() method triggers the submit event, or attaches a function to run when a submit event occurs.

What JavaScript method can you use to send a form for validation prior to submitting it?

The submit event triggers when the form is submitted, it is usually used to validate the form before sending it to the server or to abort the submission and process it in JavaScript. The method form. submit() allows to initiate form sending from JavaScript.


1 Answers

onsubmit is triggered whenever the form is about to be submitted.
onclick is triggered when the specific button is clicked.

Forms can be submitted by hitting the enter key in any input field. This would not trigger the onclick of the submit button, but it would trigger the form submit event. As such, use onsubmit.

like image 161
deceze Avatar answered Nov 13 '22 13:11

deceze