Can jQuery check whether input content has changed?

前端 未结 9 1060
轮回少年
轮回少年 2020-12-23 19:30

Is it possible to bind javascript (jQuery is best) event to \"change\" form input value somehow?

I know about .change() method, but it does not trigger

9条回答
  •  旧巷少年郎
    2020-12-23 20:14

    You can employ the use of data in jQuery and catch all of the events which then tests it against it's last value (untested):

    $(document).ready(function() {  
        $("#fieldId").bind("keyup keydown keypress change blur", function() {
            if ($(this).val() != jQuery.data(this, "lastvalue") {
             alert("changed");
            }
            jQuery.data(this, "lastvalue", $(this).val());
        });
    });
    

    This would work pretty good against a long list of items too. Using jQuery.data means you don't have to create a javascript variable to track the value. You could do $("#fieldId1, #fieldId2, #fieldId3, #fieldId14, etc") to track many fields.

    UPDATE: Added blur to the bind list.

提交回复
热议问题