JQuery UI autocomplete with hidden id field

Currently, I have an HTML form with a hidden field right before the text input. The following is a simplified version:

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

The text input was decorated with 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 function above works fine, except when the user copies and pastes information into it. Most users will copy and paste and delete Submit before the AJAX account search is even complete. The user does not know that the script needs them to select the result from the drop-down list, otherwise the hidden field will not be filled. However, most users are impatient and want to do something with a minimal click.

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

+4
source share
2 answers

An easy way to force a choice from the autocomplete menu is to intercept the form submit event and return false if #key is empty.

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

You can try using the Jorn Zafferer plugin. It has an option that you can specify mustMatch , which forces the user to select 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. 

You can then use the validator to make sure the field is relevant.

0
source

Source: https://habr.com/ru/post/1338311/


All Articles