简体   繁体   中英

jQuery, how to capture when text input has changed as a result of another event

I have a text input that is updated as a result of a button event. I would like to detect when the value in the text input has changed. See the example below:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<script  type="text/javascript">
$(document).ready(function(){
   $('#text').bind("input change paste", function(){
      console.log("text changed");
      // do something
   });

   $('#click').click (function(){
      $('#text').val('something');
   });
});
</script>

<body>
   <input id='text' type='text'>
   <input id='click' type='button' value='click'>
</body>

Later on, that button will trigger a calender so the user select a date/time which will update the text input. Since the calender is part of a library we I don't want to change it. I would like to detect when the text field gets a new value.

thanks!

I think what you're referring to is

$("#text").on("change", function(){});

take a look at this post

Since the date/time picker library you are using doesn't raise any sort of change or input event, the only way to reliable tell if the value has changed is to watch with a timer and raise the change event yourself. The following is one way to do this:

// check for changes every 100 ms
setInterval(function() {
    var lastVal = $('#text').data('last-value');
    if (typeof lastVal === 'undefined') {
        lastVal = $('#text').val();
        $('#text').data('last-value', lastVal);
    }

    if (lastVal !== $('#text').val()) {
        $('#text').change(); // trigger the change event
    }
}, 100);

// setup your change handler 
$('#text').on("input change paste", function() {
    // before doing anything else, set the last-value data property
    $('#text').data('last-value', $('#text').val());

    // do something ...
    console.log('changed!');
});

// now programmitically updating the $('#text') element will result 
// in your change handler being triggered
$('#click').click (function(){
    $('#text').val('something');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM