jQuery onchange detection

故事扮演 提交于 2019-12-20 05:33:07

问题


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?


回答1:


.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');



回答2:


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();
        }
    }
}



回答3:


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.




回答4:


if you first
input.focus(); then $.val('abcd'); a change event will be fired.
taken from jquery site.




回答5:


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"));



来源:https://stackoverflow.com/questions/5349504/jquery-onchange-detection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!