Reset form invalid values

Here’s a sample form:

<form>
  <input type="number">
  <input type="number">
  <button type="button">Reset</button>
</form>
var form = document.querySelector('form');

function detectChange() {
  var inputs = form.querySelectorAll('input');
  for (var input of inputs) {
    if (input.value) {
      return true;
    }
  }
}

form.querySelector('button').addEventListener('click', function() {
  if (detectChange() && confirm('Are you sure you want to reset?')) {
    form.reset();
  }
});

DEMO

I’d like the reset button to work even if the user enters non-numeric values.

I’m not sure I’ve understood your question. SInce you have type="number" the user is not going to be able to enter a non-numeric value.

You can do it even in Chrome: copy and paste some text into the input fields.

Right now you don’t have a reset button. You must give it a type of reset to make it a reset button.

1 Like

Thanks for the suggestion, but as you know:

You should usually avoid including reset buttons in your forms. They’re rarely useful, and are instead more likely to frustrate users who click them by mistake (often while trying to click the submit button).

The same source

Here are the requirements:

  • The button should work only when there’s a value. (a non-empty input field)
  • A confirm dialog box should appear to avoid unwanted reset of the form.

Then you might additionally check for the validity of the element:

if (input.value || input.validity.badInput) {
  return true
}
1 Like

It’s great! The following seems to work as well:

if (input.value || !input.validity.valid) {
  return true;
}
1 Like

I’m convinced to follow your advice and use a <button> element of type "reset", but control its behavior using JavaScript:

if (detectChange() && !confirm('Are you sure you want to reset?')) {
  event.preventDefault();
}

DEMO

Now the reset button clears anything, but the confirm dialog box appears only when there are real values: numbers!

When one field contains invalid text in a number field, and the other field has a number, the confirm then correctly occurs.

If you ever intend for something other than numbers to be in the form field, then don’t make it a number field. Values that aren’t valid numbers aren’t allowed to be set in number fields, and are seen as being empty.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.