Can jQuery check whether input content has changed?

前端 未结 9 1030
轮回少年
轮回少年 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:11

    There is a simple solution, which is the HTML5 input event. It's supported in current versions of all major browsers for <input type="text"> elements and there's a simple workaround for IE < 9. See the following answers for more details:

    • jQuery keyboard events
    • Catch only keypresses that change input?

    Example (except IE < 9: see links above for workaround):

    $("#your_id").on("input", function() {
        alert("Change to " + this.value);
    });
    
    0 讨论(0)
  • 2020-12-23 20:11

    You can also store the initial value in a data attribute and test it with the current value.

    <input type="text" name="somename" id="id_someid" value="" data-initial="your initial value" /> 
    
    $("#id_someid").keyup(function() {
        return $(this).val() == $(this).data().initial;
    });
    

    Would return true if the initial value has not changed.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题