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?
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.