Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset form invalid values

Here's a sample form:

var form = document.querySelector('form');

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

form.querySelector('button').addEventListener('click', function() {
  if (detectChange() && confirm('Are you sure you want to reset?')) {
    form.reset();
  }
});
<form>
  <input type="number">
  <input type="number" value="7">
  <button type="button">Reset</button>
</form>

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

like image 543
Mori Avatar asked Apr 10 '19 07:04

Mori


1 Answers

If you look at the input DOM object, there is a property badInput under validity object whose value is a boolean. For numeric entry or empty field, it's false. However it's true for non numeric values, which can interestingly be used in your case.

Note: Tested only on firefox and safari

input
|  +-- ...
|  +-- validity
|  |   +-- badInput
|  |   +-- ...
|  +-- ...

Using this knowledge you can modify the function to check for badInput to achieve what you want with minimal tweaking.

// non-empty and non default
if ((input.value && input.value != input.defaultValue) || input.validity.badInput)

var form = document.querySelector('form');

function detectChange() {
  var inputs = form.querySelectorAll('input');
  for (var input of inputs) {
    if ((input.value && input.value != input.defaultValue) || input.validity.badInput) {
      return true;
    }
  }
}

form.querySelector('button').addEventListener('click', function() {
  if (detectChange() && confirm('Are you sure you want to reset?')) {
    form.reset();
  }
});
<form>
  <input type="number">
  <input type="number" value="11">
  <button type="button">Reset</button>
</form>

Update:

update to cover:

inputs with non-empty default values

like image 184
1565986223 Avatar answered Oct 12 '22 23:10

1565986223