I have an input
field with type="number"
. After this value is changed the page will perform validation and if failed it will show a bunch of information to the visitor.
So this validation should only be done when:
- Pasting something into the box
- Typing in the box and then pressing tab to select another input
- Typing in the box and then clicking outside the box
- Pressing enter (which performs a click on the submit button)
- Clicking increment and decrement buttons
And not when:
- Typing a single digit (as the input is not complete)
Are there HTML events available for this requirement?
CodePudding user response:
I think what you might be looking for is the onblur
or focusout
event. It fires when the element will be out of focus. Basically, the opposite of onfocus
.
<input type="text" name="fname" id="fname" onblur="myFunction()">
You may want to use it in combination with other events (onclick
) which you require for the submit button.
CodePudding user response:
let input = document.querySelector("input")
input.onchange = function () {
alert("changed")
}
<input type="number">
CodePudding user response:
Did you actually try the event .onchange
/ addEventListener('change',{})
or in your case, since you are asking for an html-inline-solution: input onchange="yourFunc()"
? It sounds like that's pretty much what you want.
(.onchange
won't trigger as long as you are just typing).
Here's a very simple demo to stress the behaviour of .onchange
:
as you will see, it fulfills most of your needs:
Typing in the box and then pressing tab to select another input
Typing in the box and then clicking outside the box
Pressing enter (which performs a click on the submit button)
Clicking increment and decrement buttons
The only thing missing is triggering the event upon pasting smth in it, but the user can just press enter, click elsewhere, tab etc. to fire your function.
function fire(){
console.log("changed");
}
<input type="number" onchange="fire()">
<button>a non-functional button to focus on</button>