How to Listen/Detect Changes to an Input Value - When the Input Value Is Changed via JavaScript

Pure Javascript listen to input value change

This is what events are for.

HTMLInputElementObject.addEventListener('input', function (evt) {
something(this.value);
});

Event when input value is changed by JavaScript?

Based on @t-j-crowder and @maciej-swist answers, let's add this one, with ".apply" function that prevent infinite loop without redefining the object.

 function customInputSetter(){

var descriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value");
var originalSet = descriptor.set;

// define our own setter
descriptor.set = function(val) {
console.log("Value set", this, val);
originalSet.apply(this,arguments);
}

Object.defineProperty(HTMLInputElement.prototype, "value", descriptor);
}

Detect programmatic changes on input type text

If you're dealing with a modern browser, you can try with something like this:

var input = document.getElementById('test');
input._value = input.value;
Object.defineProperty(input, "value", {
get: function() {return this._value;},
set: function(v) {
// Do your stuff
this._value = v;
}
});

This solution is good if you actually don't expect any user input (i.e., hidden type input fields), because it's extremely destructive of the DOM basic functionality. Keep that in mind.

How do I detect when input value changes real-time in JavaScript?

Use the input event instead, as the name suggests it would fire each time an input is made, see this example on how to use the event:

let inputElem = document.querySelector('input');
inputElem.addEventListener('input', () => { console.log(inputElem.value); // Log the new value after an input is made});
<input />

Detect changed input Values of an HTML input table

You could mark each row with a data- attribute and use it to check if it changes.

For example in a given row:

<tr id="tr1" data-foo-bar="original">
<td><input type="text" onchange="change();"></td>
</tr>

When a value inside this row is changed you trigger this function:

function change(){
document.getElementById("tr1").dataset.fooBar = "modified";
}

Then you can access this attribute with:

if (document.getElementById("tr1").dataset.fooBar == "original"){
// hasn't been changed

}
else
{
// it has changed

}


Related Topics



Leave a reply



Submit