0

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.

Dhia Shalabi
  • 1,332
  • 1
  • 13
  • 29
  • Just change `$("#input-id")` to `$(document)` – Rojo Sep 28 '21 at 12:31
  • 1
    Who is removing `readonly` attribute? Put your function there. User can not remove it – Justinas Sep 28 '21 at 12:38
  • `$(document).on("input", ...` do both `change keyup paste` – Mister Jojo Sep 28 '21 at 12:39
  • That sounds a bit like an XY problem. A `readonly` property won't magically go away. So either you do that in your code, but if you know that you remove this property why can't you then listen to changes on that element? If you don't remove it and the user does this using the developer tools, then what problem do you try to solve there? – t.niese Sep 28 '21 at 12:41
  • DIAA I don't understand, you say `but I need for any input in the document` but you use the code `$('input[readonly]')` so why not just use `$('input')` – Carsten Løvbo Andersen Sep 28 '21 at 12:52
  • Maybe this can help you https://stackoverflow.com/questions/16781778/detecting-attribute-change-of-value-of-an-attribute-i-made – Carsten Løvbo Andersen Sep 28 '21 at 12:53

2 Answers2

1

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.

Gil
  • 1,794
  • 1
  • 12
  • 18
0

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!