Reputation: 31
I want to execute javascript that's in the "onchange" attribute of an html element. So..
<input id="el" type="text" onchange="alert('test');" value="" />
Using that example I'd like to execute the alert('test');
portion via jQuery, the problem is the .change()
event handler isn't working, because I want to execute it after another element changes it's value. So..
$('#el').val('test');
This is when I'd like to execute the onchange. After that .val
val has been called. Any ideas?
Upvotes: 1
Views: 4451
Reputation: 2043
I Would redesign and start using knockout.js plugin which is using data-bind where let u use all the binding pretty easy.
sample code below:
var ViewModel = function(first, last) {
this.firstName = ko.observable(first);
this.lastName = ko.observable(last);
this.fullName = ko.computed(function() {
// Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
return this.firstName() + " " + this.lastName();
}, this);
};
ko.applyBindings(new ViewModel("Planet", "Earth"));
Upvotes: -1
Reputation: 8402
I think it makes sense that the onchange event ALWAYS fires when the value of the field changes. Thus, I would change the val
function in JQuery itself rather than make a custom function. That way, you don't have to worry about which function you use to set the value of an object, and don't have to go change all of your val
calls if you've already used JQuery to code your app. Here's the code:
//Store the old val function
$.fn.custom_oldVal = $.fn.val;
//Update the val function to fire the change event where appropriate:
$.fn.val = function(value) {
if(value == null || value == undefined){
return this.custom_oldVal();
} else {
//Only call onchange if the value has changed
if(value == this.custom_oldVal()){
return this;//Return this object for chain processing
} else {
return this.custom_oldVal(value).change();
}
}
}
Upvotes: 2
Reputation: 21201
if you first
input.focus();
then $.val('abcd');
a change event will be fired.
taken from jquery site.
Upvotes: 0
Reputation: 37751
I had the same problem a while ago, but couldn't find any good solutions to it. It seems the best solution is to do a "pull" on the input, or to fire your onchange function (like Domenic shows) from the code that actually changes the content of the input.
Upvotes: 0
Reputation: 112827
.val()
does not trigger change
events. You need to do so yourself, manually. For example:
$('#el').val('test').change();
You can encapsulate this in a small jQuery plugin like so:
(function ($) {
$.fn.changeVal = function (text) {
this.val(text).change();
};
}(jQuery));
$('#el').changeVal('test');
Upvotes: 7