In javascript, how to launch a function whenever the value of a hidden input is changed…
- User
In javascript, how to launch a function whenever the value of a hidden input is changed by another function I can't access the code of ?
- Assistant
You can achieve this by using the
MutationObserverAPI in JavaScript.MutationObserverprovides a way to observe changes in the DOM and execute a callback function whenever a specific type of mutation occurs.Here's an example of how you can use
MutationObserverto launch a function whenever the value of a hidden input is changed by another function that you can't access:javascript - User
Reusing your preceding code example, make your code log the value of the field.
- Assistant
Sure, you can update the code by adding a line to log the value of the hidden input field whenever it is changed. Here's the updated code:
javascript// Select the hidden input element const hiddenInput = document.querySelector('#hidden-input'); // Create a new instance of MutationObserver and pass in a callback function const observer = new MutationObserver((mutationsList) => { for (let mutation of mutationsList) { if (mutation.type === 'attributes' && mutation.attributeName === 'value') { const newValue = mutation.target.getAttribute('value'); console.log('New value: ', newValue); // Call your function here whenever the value of the hidden input is changed yourFunction(); } } }); // Define the options for the observer const config = { attributes: true, attributeOldValue: true }; // Start observing the hidden input for changes in the value attribute observer.observe(hiddenInput, config);