Bootstrap Typeahead Only Allow List Values

前端 未结 4 1540
轻奢々
轻奢々 2020-12-14 09:52

Is it possible to limit a user\'s selection to the predefined data-source items for a Bootstrap Typeahead item? So if the user types something that is not in the data-source

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 10:54

    I solved this problem a little differently - most of the time you need to capture the id of the suggested options, to post to a subsequent web service call, etc.

    I decided to blank out a hidden field when the typeahead async call starts, and set the value of the hidden field to the datum.id on the autocompleted or selected typehead events.

    When submitting the form, I simply check if the hidden field has a value or not, if it doesn't, then the user never selected a suggested option.

    I named the hidden field by adding a _id to it based on the name of the typeahead field, and then used this code in the onAutocompleted and onSelected functions

    I specified those functions by adding:

    .on('typeahead:selected', onAutocompleted)
    .on('typeahead:autocompleted', onSelected)
    

    in the code that adds the .typeahead functionality to the input field.

    var n = $(this).attr('name')+'_id';
    $('input[name="' + n + '"]').val(datum.id);
    

    The typeahead documentation talks about there being three parameters that are passed to the autocompleted and selected functions, the event, the datum, and the name, but I never saw the name being passed, and that's why I used the $(this).attr('name') mechanism to get the name of the field.

提交回复
热议问题