Force a user to select from JQuery UI Autocomplete and populate a hidden field after selecting
Asked Answered
D

5

13

I have a large HTML form that contains many fields that need an autocomplete for accounts. I tag these fields with the class AccountLookup and jQuery does the dirty work for the autocomplete:

$(".AccountLookup").autocomplete({
    source: function (request, response) {
        $.ajax({
            url: "Lookup.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
                    }
                }))
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
    },
    minLength: 3
});

Now, when a user selects something from the autocomplete I need it to populate a hidden field just BEFORE the tagged input field; probably using something like:

$(this).prev().val(item.Key);

How do I incorporate this functionality? Also, how do I force a user to select from the auto complete? (All the values are pre-defined, the user cannot add new ones.)

EDIT: As far as I understand from inspecting the DOM, the select option is currently filling in the hidden form field.

select: function (event, ui) {
    $(this).prev().val(ui.item.key);
}
Douty answered 21/12, 2010 at 17:39 Comment(0)
C
3
$(".AccountLookup").autocomplete({
   /*...*/
}).result(function(event, item) {
   $(this).prev().val(item.Key);
});

You could also use a jQuery validate to ensure that the field is populated.

Cd answered 21/12, 2010 at 17:47 Comment(0)
P
17

I know this is an old post--- but I ran into it in trying to solve a similar problem (forcing the user to select an item from the list)...

        $("#ac").autocomplete({
            source: function (req, resp) {
                   //add code here...
            },
            select: function (e, ui) {
                $(this).next().val(ui.item.id);
            },
            change: function (ev, ui) {
                if (!ui.item)
                    $(this).val("");
            }
        });
Professorship answered 27/9, 2012 at 14:55 Comment(0)
C
3
$(".AccountLookup").autocomplete({
   /*...*/
}).result(function(event, item) {
   $(this).prev().val(item.Key);
});

You could also use a jQuery validate to ensure that the field is populated.

Cd answered 21/12, 2010 at 17:47 Comment(0)
K
1

for force selection, you can use "change" event of Autocomplete

        var availableTags = [
            "ActionScript",
            "AppleScript"
        ];
        $("#tags").autocomplete({
            source: availableTags,
            change: function (event, ui) {
                if(!ui.item){
                    //http://api.jqueryui.com/autocomplete/#event-change -
                    // The item selected from the menu, if any. Otherwise the property is null
                    //so clear the item for force selection
                    $("#tags").val("");
                }

            }

        });
Kancler answered 17/12, 2012 at 15:33 Comment(0)
O
0

For the selection action, try using the formatItem option. You can format each result to have an onclick event that will populate the other textbox.

For the forcing to select from autocomplete, you need to use the mustMatch option.

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

Odo answered 21/12, 2010 at 17:45 Comment(2)
I tried using the mustMatch option, but it doesn't seem to be working. I can still input values not defined by the server and submit the form.Douty
The jQuery UI Autocomplete DOES NOT have the "mustMatch" option. I am using a completely different plugin from the one you are talking about.Douty
M
0

I ran into this same problem quite awhile ago and some post helped me along with it. I have since modified the code as I found that there were cases I wanted one or more fields to fill in from the information returned. In the select option of the autocomplete I added a function.

select: function (e, ui) {ReSetField({'txtID':'id','txtPrice':'price' [,etc...]}, ui)  }

The function "ResetFields" then takes in a JSON list of element names paired with fieldnames and uses the fieldnames to match the elements in the ui object. The value can then be pulled from the ui item and put into the html element.

    function ReSetField(_flds, _vals) {
  //Set up the flds to be reset with values passed in.  
  try {
    if (_flds != undefined) {
      if ($.type(_flds) == 'string') {
        _flds = JSON.parse(_flds);
      };
      var _fld = null;
      var _val = '';
      $.each(_flds, function (index) {
        if (index.length > 0) {
          _fld = '#' + index;   //Set the forms field name to set  
          _val = _flds[index]; //Pick up the field name to set the fields value 
          $fld = $(_fld);
          $fld.val(_vals.item[_val]); //Set the fields value to the returned value             
          }
        }
      })
    };
  }
  catch (e) {
    alert('Cannot set field ' + _fld + '.');
  } 
}

By sticking the "fieldlist" into the HTML element as an attribute like "fieldlist" and using a class like "comboBox" I can then use a single function to find all ComboBox elements and set up the autocomplete on a form reducing the amount of code required to handle 2 or more lookups on a form.

Mintamintage answered 28/1, 2015 at 19:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.