mhenry
mhenry

Reputation: 1487

jQuery UI Autocomplete with Hidden ID Field

Currently I have an HTML form with a hidden field right before a text input. A simplified version is below:

<form>
    <input type="hidden" name="key" id="key" />
    <input type="text" name="account" id="account" />
    <input type="button" value="Submit" />
</form>

The text input has been decorated with the jQuery UI Autocomplete.

$("#account").click(function () {
    $(this).prev().val('');
    $(this).val('');
}).autocomplete({
    source: function (request, response) {
        $.ajax({
            url: "AJAX.asmx/GetAccounts",
            data: "{ 'Search': '" + request.term + "' }",
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataFilter: function (data) { return data; },
            success: function (data) {
                response($.map(data.d, function (item) {
                    return {
                        value: item.Value,
                        key: item.Key
                    }
                }))
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus + ": " + errorThrown);
            }
        });
    },
    select: function (event, ui) {
        $(this).prev().val(ui.item.key);
    },
    change: function (event, ui) {
        if ($(this).prev().val() == '') {
            $(this).val('');
        }
    }
});

The script above functions perfectly, except for when a user copy and pastes information into it. Most users will copy and paste and hit Submit well before the AJAX account search has even finsihed. The user does not know that the script needs them to select a result from the drop down or else the hidden field will not populate. However, most users are impatient and want to do things with minimal clicking.

How can I intercept a paste that has one result? How can I do this before the user clicks the submit button?

Upvotes: 4

Views: 4711

Answers (2)

Adolph Trudeau
Adolph Trudeau

Reputation: 361

A simple way to enforce selecting from the autocomplete menu is to intercept the form's submit event and return false unless #key has something in it.

//assuming there is only one form within web page
$('form').submit(
    function(){
        if($('#key').val() == '') {
            return false
        } else {
            return true
        }
    });

Upvotes: 3

Victor
Victor

Reputation: 4721

You could try using Jorn Zafferer's plugin. It has an option that you canspecify mustMatch which forces the user to pick from the list.

http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_dataoptions

If set to true, the autocompleter will only allow results that are presented by the backend. Note that illegal values result in an empty input box.

Then you could use a validator to make sure the field has a value.

Upvotes: 0

Related Questions