Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
170
rated 0 times [  174] [ 4]  / answers: 1 / hits: 22923  / 13 Years ago, mon, january 9, 2012, 12:00:00

The onchange event is triggered only when the USER enters some value. Why isn't possible to fire the event when I change the value automatically via Javascript ? Is there an alternative ?



Animation:



enter



Code:



<!DOCTYPE html>

<html>
<head>
<script>
document.addEventListener (DOMContentLoaded, function () {
var input = this.getElementsByTagName (input)[0];
var div = this.getElementsByTagName (div)[0];
var i = 0;
var seconds = 5;

div.innerHTML = The following input should fire the event in + seconds + seconds;

var interval = window.setInterval (function () {
i ++;

if (i === seconds) {
window.clearInterval (interval);

input.value = Another example;

div.innerHTML = Nothing ! Now try change the value manually;
}
else {
div.innerHTML = The following input should fire the event in + (seconds - i) + seconds;
}
}, 1000);

input.addEventListener (change, function () {
alert (It works !);
}, false);
}, false);
</script>

<style>
body {
padding: 10px;
}

div {
font-weight: bold;
margin-bottom: 10px;
}

input {
border: 1px solid black;
border-radius: 3px;
padding: 3px;
}
</style>

<title>Event</title>
</head>

<body>
<div></div>
<input type = text value = Example />
</body>
</html>


Thanks


More From » triggers

 Answers
6

The vast majority of the time, you don't want an event to be fired when you change the value with code. In those cases where you do, you can fire a synthetic event on modern browsers via dispatchEvent. More here.



So in your specific example:



input.value = Another example;
var event = document.createEvent(UIEvents); // See update below
event.initUIEvent(change, true, true); // See update below
input.dispatchEvent(event);


Live demo



Update: As Benjamin noted, since the above was written, initUIEvent has been replaced with the UIEvent constructor, so that would be:



input.value = Another example;
var event = new UIEvent(change, {
view: window,
bubbles: true,
cancelable: true
});
input.dispatchEvent(event);


Live demo



Alternately, you can always just call whatever function you've bound to the change event directly, which is usually what I'd do. But sometimes you want to use actual events (for instance, when using the observer pattern) and ensure that anyone who is listening for the change is notified.


[#88139] Sunday, January 8, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
farrahsavannahl

Total Points: 418
Total Questions: 108
Total Answers: 90

Location: Bonaire
Member since Sat, May 1, 2021
3 Years ago
;