Home > Designing, Others > What’s New With Forms in 2022?

What’s New With Forms in 2022?

September 8th, 2022 Leave a comment Go to comments

Browsers are constantly adding new HTML, JavaScript and CSS features. Here are some useful additions to working with forms that you might have missed…

requestSubmit()

Safari 16 will be the final browser to add support for requestSubmit.

Before we look at how .requestSubmit() works, let’s remind ourselves how programmatically submitting a form with JavaScript works when using the .submit() method. Submitting a form with submit() does not trigger a submit event. So in the following code, the form is submitted, preventDefault() has no effect, and nothing is logged to the console:

const form = document.forms[0];
form.addEventListener('submit', function(event) {
  // code to submit the form goes here
  event.preventDefault();
  console.log('form submitted!');
});

document.querySelector('.btn').addEventListener('click', function() {
  form.submit();
})

.submit() will also ignore any HTML form validation. Given the following markup, the form will be submitted when the input is empty even though the input has a required attribute:

<form>   
  <label for="name">Name</label>
  <input required name="name" id="name" type="text">
</form>

.requestSubmit() is an alternative way to submit a form using JavaScript, but in contrast to .submit(), HTML form validation will prevent the form from being submitted. If all the data entered in the form passes validation, the submit event will be fired, meaning “form submitted!” would be logged to the console in the following example:

form.addEventListener('submit', function(event) {
  event.preventDefault();
  console.log('form submitted!');
});

document.querySelector('.btn').addEventListener('click', function() {
  form.requestSubmit();
})

You could already achieve this by programmatically clicking the form’s submit button, but requestSubmit is perhaps a more elegant solution.

submitter property of submit event

The SubmitEvent.submitter property gained full cross-browser support with the release of Safari 15.4. This read-only property specifies the

Categories: Designing, Others Tags:
  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.