This seems like a relatively simple thing but I can\'t find anything anywhere on how to do it. I have a modal that opens with a disabled input while waiting for async data.
I know that this isn't the best way, but here I go:
var timeToCheck = 1000, past = 0;
function wait_enable (element) {
var timer = setInterval(function(){
if(element.is(":enabled")){
element.focus();
clearInterval(timer);
}
/* //here you can set a limit
past += timeToCheck;
if (past > limit) {
clearInterval(timer);
}
*/
}, timeToCheck);
}
var textInput = $("input");
wait_enable(textInput);
$("button").on("click", function(){
textInput.prop("disabled", false);
});
I once had a project with it, but I lost the motivation to do it.
I searched for a way to do that kind of stuff, and I found that MutationObserver
should be a good way to do it.
Take a look : MutationObserver
And maybe there too : Mutation Events
I hope I understood your question correctly.
Unfortunately, there's no such thing as onenabled
or ondisabled
listeners. Input fields can only be enabled/disabled by JavaScript once the page has loaded (or by some user which is messing up with your HTML in his developer tools' inspector). For this reason, if you want to detect those changes you'll have to use a MutationObserver, and listen for attribute mutations of the element you want, to check whenever the disabled
property gets added to your input field.
Here's an example of what I'm talking about:
var btn = document.getElementById('toggle'),
input = document.getElementById('inp');
// This is just to demonstrate the behavior of the MutationObserver
btn.addEventListener('click', function() {
if (input.disabled) input.disabled = false;
else input.disabled = true;
});
var observer = new MutationObserver(function(mutations) {
for (var i=0, mutation; mutation = mutations[i]; i++) {
if (mutation.attributeName == 'disabled') {
if (mutation.target.disabled) {
// The element has been disabled, do something
alert('You have disabled the input!');
} else {
// The element has been enabled, do something else
alert('You have enabled the input!');
}
}
};
});
// Observe attributes change
observer.observe(input, {attributes: true});
<p>Try clicking the button to disable/enable the input!</p>
<input id="inp" type="text" placeholder="Write something...">
<button id="toggle">Toggle</button>
The MutationObserver
object is a newly introduced feature, and it isn't supported by old versions of some browsers: you can check the compatibility with any browser on this page.