b85411
b85411

Reputation: 10010

Bootstrap - add a loading state to an input box?

I have got an input box:

        <div id="myDiv" class="col-sm-10">
            {# Autocomplete text box #}
            <input class="form-control" type="text" name="myAutoComplete" id="MyAutocomplete1">
        </div>

And I have some jQuery to initialise this textbox so it becomes an "autocomplete" box, where a user types in a few letters and can select a match from the list.

When the jQuery loads the data (there is quite a bit, roughly 10,000 entries) it takes a bit of time - maybe 5 seconds. If the user types into the autocomplete box during this time, obviously the autocomplete doesn't work because the data hasn't finished loading.

How can I add a "loading state" to this input text field? I want a similar sort of functionality to http://getbootstrap.com/javascript/#buttons - where after a period of time instead of saying "Loading..." it just becomes active.

Thanks

Upvotes: 1

Views: 2890

Answers (1)

b85411
b85411

Reputation: 10010

Figured it out:

I made this JS function:

function addLoadingToTextbox(textboxes, text, onload) {
    for (i = 0; i < textboxes.length; i++) {
        if (onload) {
            $(textboxes[i]).prop('disabled', 'true'); // disable
            $(textboxes[i]).val(text); // add loading text
        }

        else {
            $(textboxes[i]).removeAttr('disabled'); // re-enable
            $(textboxes[i]).val(''); // remove loading text
        }
    }
}

Then just call it like this when you have started loading data (this will disable the box and make it say LOADING.....):

addLoadingToTextbox([$('#MyAutocomplete1')], 'LOADING.....', true);

And to reverse that, run:

addLoadingToTextbox([$('#MyAutocomplete1')], '', false);

Because the textboxes parameter takes an array, you can pass in multiple elements at once (which is handy if you are doing a bulk-load for data).

Hopefully that helps someone else.

Upvotes: 2

Related Questions