I need a change event to fire on an element without regard of how the element value was changed.
My use case here is that I need to change elements on a form whenever a particular textbox changes value. The problem is that the element is populated by another button (a calendar button that lets the user choose a date which is then inserted in the first textbox).
Using the sample below, I need to know when "date1" changes so I can update "date2". I won't know the ID of the button--its dynamically generated by another tool--so I can't attach anything to that.
I have the following HTML:
<input type="text" id="date1" value="" />
<input type="button" id="but1" value="click me" />
<br/>
<input type="text" id="date2" value="" />
And this JavaScript:
$(function () {
$("#but1").click(function () {
$("#date1").val(new Date().toLocaleDateString());
});
$("#date1").change(function () {
var d = new Date($("#date1").val());
$("#date2").val(d.addDays(7));
});
});
Date.prototype.addDays = function (days) {
var current = this;
current.setDate(current.getDate() + days);
return current;
};
Here is a jsfiddle I was using: http://jsfiddle.net/mYWJS/7/
Update: I added a DIV wrapper to the jsfiddle example in hopes that might inspire another solution. I couldn't find a way to utilize it myself but my JavaScript skills are rather mediocre.
In regards to Fabricio's comment about DOM mutations, is there a DOM mutation solution that is somewhat browser independent? There is no way for me to predict with certainty the browser that will be used here. I'm not too concerned about IE6, but the few solutions I've seen for DOM mutations seem to focus on Chrome.
changeonly fires for text inputs when the input loses focus after having its value changed after gaining focus. No focus = no change event. You can trigger a synthetic.change()event after changing it from your JS, but if you really need to watch over an input's value, you will need a DOM Mutation Observer which is mostly a hack.