- When we create the code that assigns this property from a similar element, we can call it as a method.
- This feature can be read continuously with the change event to the date input.
- I wanted to try something with MutationObserver, but it seems to me that it is no different from calling it as the method I mentioned at first.
<div class="inputs">
<input type="date"/>
</div>
<button>Add</button>
document.querySelector('button').addEventListener('click', function () {
let clone = `<input type="date"/>`;
document.querySelector('.inputs').insertAdjacentHTML('beforeend', clone);
})
document.querySelectorAll('input[type=date]').forEach(input=>{
input.max = new Date().toISOString().split("T")[0];
})
But apart from these, is there a method that we can run in a smoother dynamic structure?
In my opinion for this simple operation MutationObserver is too much expensive.
The main problem with your code, is that the
document.querySelectorAll('input[type=date]').forEach...is not "reactive", but executed only once, at every script tag/file parsing. Indeed for the first one input, added statically ( or server side ) in your html it works, but for the others added dynamically with the button it won't work.So you must operate inside the
clicklistener, like you did. But instead of simply create an html string you can create anHTMLInputElement, set wathever property you want directly and append it.Now you have to manage the inputs which are yet in the page.
If your view is rendered by a server script, you could simply add the max attribute there.
If you want to add it via javascript, you can keep this line, and is going to work for multiple elements to:
Working example:
--edit: Another example, with more consistent date value: