PDA

View Full Version : Reset form invalid values



Rain Lover
04-10-2019, 07:56 AM
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 (https://jsfiddle.net/Mori/Lpzdrsk1/)

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

keyboard
04-10-2019, 01:13 PM
It only accepts numbers because in the form in the html the input type is set to number.

Change

<form>
<input type="number">
<input type="number">
<button type="button">Reset</button>
</form>


to

<form>
<input type="text">
<input type="text">
<button type="button">Reset</button>
</form>

Rain Lover
04-10-2019, 05:17 PM
It only accepts numbers because in the form in the html the input type is set to number.
Actually you can do it even in Chrome: copy and paste some text into the input fields.

keyboard
04-10-2019, 10:46 PM
Actually you can do it even in Chrome: copy and paste some text into the input fields.

Yes, you can input text into the box, but it isn't a valid input (I'm not 100% sure on this, I'm just going off my own testing while I was editing the code you put).

Try running the following code -


<!DOCTYPE html>
<html>
<head>

</head>
<body>
<input type="number" id="inputNumber">
<input type="button" id="inputButton" value="Test">

<script type="text/javascript">
document.getElementById("inputButton").onclick = function() {
var value = document.getElementById("inputNumber").value;
alert(value);
};
</script>

</body>
</html>

If you enter a number into the input it alerts the number. If you enter text or a combination of text and numbers, the alert is empty. The other difference in chrome is that it adds a little increment and decrement arrow to the input field. On mobile it gives you a keypad to enter a number instead of the default keyboard.
6340


So the reason your original code wasn't working was this line

if (input.value) {
return true;
}
If you enter a string into the number input then input.value is empty and so the detectChange doesn't return true.
If you change it to a text input, that won't be a problem.