I have a basic text input field and, for data analytics purposes, I want to track every time a user edits the text in that field as they edit it. I have this code so far:
var input = document.querySelector("#inputId");
input.oninput = function (e) {
alert("changed");
}
The issue is that this fires every time the user deletes or adds a character, whereas I only want to know one single time that they are changing the text in the text field. Is there a way to achieve this? I am new to jQuery and JavaScript so any direction would be really appreciated, thank you!
You can try using Parameters option once: true
:
once
: A Boolean indicating that the listener should be invoked at most once after being added. Iftrue
, the listener would be automatically removed when invoked.
Please Note: Internet Explorer yet to support this parameter characteristic.
var input = document.querySelector("#inputId"); input.addEventListener('input', () => { alert("changed"); }, { once: true });
<input id="inputId"/>
If you only want the event handler to fire once per element, then you need to remove the event handler the first time it runs:
var input = document.querySelector("#inputId");
input.addEventListener('input', yourFunc);
function yourFunc(e) {
alert("changed");
this.removeEventListener('input', yourFunc);
}
Note the use of addEventListener()
and removeEventListener()
instead of the outdated oninput
property.
As you've tagged jQuery in the question you can also achieve it in this manner, using one()
:
$('#inputId').one('input', function() {
alert('changed');
});
It sounds like you want to bind to the onchange
event instead: it is fired when the input value is "finalized" by the user, eg when he/she blurs from the field:
var input = document.querySelector("#inputId"); input.addEventListener('change', (e) => console.log('changed', e.target.value));
<input type="text" id="inputId" />
Just remove function when it call
let input = document.querySelector("#inputId"); input.oninput = function (e) { alert("changed"); input.oninput = undefined; }
<input id="inputId">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.