最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Trigger a function when an element gets enableddisabled - Stack Overflow

programmeradmin4浏览0评论

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 want to know when that input becomes enabled to I can focus the input. This is what I'm trying to accomplish. Think of it as a global modal open handler:

$('.modal').on('shown.bs.modal', function (event) {
    var textInput = $(event.target).find('input[type=text]:visible').first();
    if (textInput.is(':disabled'))
    {
        textInput.on('<<<<<enabled>>>>>', function(){
            textInput.off('<<<<<enabled>>>>>');
            textInput.focus();
        });
    }
    else
    {
        textInput.focus();
    }
});

Is there not an event that gets triggered when an input becomes enabled/disabled?

<input type="text" class="form-control txtUserSearch" data-bind="value: userFilter, event: { keyup: FilterUsers }, enable: AvailableUsers().length > 0">

Which becomes enabled if there are users returned in an async request.

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 want to know when that input becomes enabled to I can focus the input. This is what I'm trying to accomplish. Think of it as a global modal open handler:

$('.modal').on('shown.bs.modal', function (event) {
    var textInput = $(event.target).find('input[type=text]:visible').first();
    if (textInput.is(':disabled'))
    {
        textInput.on('<<<<<enabled>>>>>', function(){
            textInput.off('<<<<<enabled>>>>>');
            textInput.focus();
        });
    }
    else
    {
        textInput.focus();
    }
});

Is there not an event that gets triggered when an input becomes enabled/disabled?

<input type="text" class="form-control txtUserSearch" data-bind="value: userFilter, event: { keyup: FilterUsers }, enable: AvailableUsers().length > 0">

Which becomes enabled if there are users returned in an async request.

Share Improve this question edited Apr 14, 2015 at 17:43 Marco Bonelli 69.3k21 gold badges126 silver badges145 bronze badges asked Apr 14, 2015 at 15:22 jensengarjensengar 6,16719 gold badges60 silver badges94 bronze badges 9
  • 1 What disables/enables it? – user1017882 Commented Apr 14, 2015 at 15:24
  • This is a knockoutjs app so when the data is available knockout enables it. – jensengar Commented Apr 14, 2015 at 15:25
  • So where is the async data coming from? You'd have to hook into whatever methods are available for the async function, and without posting that, this is impossible to answer ? – adeneo Commented Apr 14, 2015 at 15:25
  • 2 Have you checked the knockout api/docs for any callbacks you have available? More often than not, well established libraries like knockout will realise you have these kinds of requirements and will expose events or callbacks for you to use. – user1017882 Commented Apr 14, 2015 at 15:25
  • 1 It's difficult to be more specific until you post, more specifically, about what knockout feature you're using. Something in knockout that you're using is affected the enabled state of your element, that 'something' is a big point in the right direction for you. – user1017882 Commented Apr 14, 2015 at 15:27
 |  Show 4 more comments

3 Answers 3

Reset to default 16

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>

Additional info

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.

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.

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);
});
发布评论

评论列表(0)

  1. 暂无评论