开发者

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

开发者 https://www.devze.com 2023-01-31 11:19 出处:网络
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:

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: it开发者_开发知识库em.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);
}


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("");
            }
        });


$(".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.


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("");
                }

            }

        });


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消