Home > other >  Detect <input type="text" readonly> changing `attribute` (immediately) using JQuery?
Detect <input type="text" readonly> changing `attribute` (immediately) using JQuery?

Time:09-28

I am using java-script to build a web page and I have multiple inputs of type text with read-only attribute and I want to detect if any input has changed in its attributes for example if any input has removed its read-only attribute then do some thing with that input.

Note: I am going to change the read-only attribute using java-script code. And I want another code to detect that change of the attribute read-only.

I have tried this

  $('input[readonly]').attrchange({
    trackValues: true,
    callback: function (event) { 
  
    }   

but I need for any input in the document.

CodePudding user response:

I don't know if this is an answer, but I can't put all of it in a comment.

Also, implementing this probably won't be as smooth and easy as in jQuery.

You can set a Mutable Observer that will detect any change in the elements. The observer is set on the parent and you can choose what to detect. This is what screen readers do in order to adapt to any changes in the page. The catch is that you'll need to learn this a little bit before you could use it.

CodePudding user response:

You can use mutation observers to detect any change on the elements you want!

A simple example that may need change depending on your needs follows:

//Get all input elements
var inputs = document.getElementsByTagName('input');

//This is the callback function on when the filtered attribute changes
const observer = new MutationObserver(function (mutations, observer) {
   //Here you can write any code to trigger when the mutation happens.
});

//We bind the observer to observe all the changes in the readonly attribute
observer.observe(inputs, {
  attributes: true,
  attributeFilter: ['readonly']
});

Note that i did not test the code above so it may need any particular change!

  • Related