Detect If a Field Is Updated With JavaScript or Jquery

Detect if a field is updated with JavaScript or jQuery

So, according to your edits/comments from other answers, you cannot trigger change manually.

A MutationObserver would be a good way to solve this, except they can't observe input value changes, as explained here.

Your only way out, as far as I can tell, is using setInterval to compare the current value with the old one every few milliseconds. A bit ugly and not optimal at all, but does the job. Here's a sample:

$(function() {  setTimeout(function() {    $('#long').val('90.000');  }, 1000);    $('#long').on('change', function() {    alert('changed');  });    // Store the current value  $('#long').data('oldVal', $('#long').val());    // Every 100ms, trigger `change` event whenever new value != old  setInterval(function() {    if ($('#long').val() !== $('#long').data('oldVal')) {      $('#long').trigger('change');      $('#long').data('oldVal', $('#long').val());    }  }, 100);    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><input type="text" id="long">

Can jQuery check whether input content has changed?

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

Determine what field changed via javascript

Try:

$('input:checkbox').unbind('change'); // Do this after the form bind

Or

// Inside the change method
if (!$(this).is('input:checkbox')) {
_changesMade = true;
}

Detect input value change made by jQuery function

Overview

In reply to my question on your question, you said:

I'm trying to detect changes made to the value via code.

There is no event triggered when that happens. You either have to trigger one, or poll, or don't worry about the change until/unless you have to (your use case doesn't seem to allow this third option).

Triggering your own event

If you control the code setting the value, jQuery makes it easy to trigger and handle your own events. When setting the value:

$("#someField").val("newValue").trigger("code-change");

To handle the change:

$("some relevant selector").on("code-change", function() {
// Handle it here
});

Although you can trigger the change event (just change the name above), beware unintended consequences if code handling the event may be expecting a real end-user event.

(function() {  "use strict";    // Watch for 'change'  $("input").on("change", function() {    display("Saw 'change'");  });    // Watch for 'code-change'  $("input").on("code-change", function() {    display("Saw 'code-change'");  });    // Watch for either  $("input").on("change code-change", function() {    display("Saw either 'change' or 'code-change'");  });    // Change it on button press  $("#btn-change").on("click", function() {    var el = $("#theElement");    var val = el.val();    switch (val.length) {        case 0:          val = "some value";          break;        case 1:          val = val + val;          break;        default:          val = val.substring(1) + val.substring(0, 1);          break;    }    el.val(val).trigger("code-change");  });    function display(msg) {    $("<p>").html(String(msg)).appendTo(document.body);  }})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><p>Experiment with changing the value as a user (remember to leave the field), and with changing it using the button.</p><div><input id="theElement" value="Initial value" type="text"></div><div><input id="btn-change" type="button" value="Change It"></div>

jQuery check if select field changed

You don't need inner each loop. Plus $(this)[0] can be optimised to just this:

$('select').on('change', function () {            var isDirty = !this.options[this.selectedIndex].defaultSelected;
if (isDirty) { alert("has changed"); } else { alert("default value"); }});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><select name="" id="">    <option value="1">Label 1</option>    <option value="2" selected>Label 2</option>    <option value="3">Label 3</option>    <option value="4">Label 4</option></select>

Detect all changes to a <input type="text"> (immediately) using JQuery

Unfortunately, I think setInterval wins the prize:

<input type=text id=input_id />
<script>
setInterval(function() { ObserveInputValue($('#input_id').val()); }, 100);
</script>

It's the cleanest solution, at only 1 line of code. It's also the most robust, since you don't have to worry about all the different events/ways an input can get a value.

The downsides of using 'setInterval' don't seem to apply in this case:

  • The 100ms latency? For many applications, 100ms is fast enough.
  • Added load on the browser? In general, adding lots of heavy-weight setIntervals on your page is bad. But in this particular case, the added page load is undetectable.
  • It doesn't scale to many inputs? Most pages don't have more than a handful of inputs, which you can sniff all in the same setInterval.

Listen for input value changed by JavaScript without polling

The solution that GracefulLight posted here that Rory put us onto does work.

You can redefine the object's value property, enabling you to do whatever you like when the value property is set.

Object.defineProperty(document.querySelector(".my-object"), "value", {
set: function(newValue) {
console.log("Object's value property has changed");

// do something
this.style.borderColor = "#228B22";

// make sure the value is still passed to the input to be output
return this.defaultValue = newValue;
}
});


Related Topics



Leave a reply



Submit