HTML.form.guide

What does it mean when you have action attribute as javascript void(0)

html form action javascript form action javascript void 0

When creating a form in HTML, the action attribute specifies the URL of the page where the form data should be submitted to. However, in some cases, you may want to use JavaScript to handle the form submission instead of submitting it to a server. In these cases, you can use javascript:void(0) as the value of the action attribute.

javascript:void(0) is a special syntax in JavaScript that does nothing when executed. By setting the action attribute to javascript:void(0), you are telling the browser not to submit the form to a server but instead to execute a JavaScript function when the form is submitted.

To use javascript:void(0) as the value of the action attribute, you need to define a JavaScript function that will handle the form submission. For example, you can define a function called submitForm() that will handle the form submission as follows:

<form action="javascript:void(0)" onsubmit="submitForm()">
  <!-- form fields -->
  <input type="submit" value="Submit">
</form>

In this example, the action attribute is set to javascript:void(0), and the onsubmit attribute is set to submitForm(). This means that when the user submits the form, the submitForm() function will be executed instead of submitting the form to a server.

The function submitform() can access the form data using the document.forms collection or getElementById() and perform any necessary actions. For example, you can use the FormData API to serialize the form data and send it to a server using an AJAX request.

function submitForm() {
  var form = document.forms[0];
  var formData = new FormData(form);
  // perform AJAX request to send formData to server
  // ...
}

See an example of handling form submission data using Javascript function in this detailed tutorial: Form Action Javascript Example

In summary, javascript:void(0) is used as the value of the action attribute to indicate that a JavaScript function should handle the form submission instead of submitting the form to a server. The JavaScript function can access the form data and perform operations, such as sending the data to a server using an AJAX request.

See Also