jQuery UI AutoComplete: Only allow selected valued from suggested list

前端 未结 9 1947
误落风尘
误落风尘 2020-11-30 22:48

I am implementing jQuery UI Autocomplete and am wondering if there is any way to only allow a selection from the suggested results that are

相关标签:
9条回答
  • 2020-11-30 23:40

    Ajax submission and handling

    This will be of use to some of you out there:

    $('#INPUT_ID').autocomplete({
        source: function (request, response) {
            $.ajax({
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                url: autocompleteURL,
                data: "{'data':'" + $('INPUT_ID').val() + "'}",
                dataType: 'json',
                success: function (data) {
                    response(data.d);
                },
                error: function (data) {
                    console.log('No match.')
                }
            });
        },
        change: function (event, ui) {
            var opt = $(this).val();
    
            $.ajax({
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                url: autocompleteURL,
                data: "{'empName':'" + name + "'}",
                dataType: 'json',
                success: function (data) {
                    if (data.d.length == 0) {
                        $('#INPUT_ID').val('');
                        alert('Option must be selected from the list.');
                    } else if (data.d[0] != opt) {
                        $('#INPUT_ID').val('');
                        alert('Option must be selected from the list.');
                    }
                },
                error: function (data) {
                    $(this).val('');
                    console.log('Error retrieving options.');
                }
            });
        }
    });
    
    0 讨论(0)
  • 2020-11-30 23:48

    You could also use this:

    change: function(event,ui){
      $(this).val((ui.item ? ui.item.id : ""));
    }
    

    The only drawback I've seen to this is that even if the user enters the full value of an acceptable item, when they move focus from the textfield it will delete the value and they'll have to do it again. The only way they'd be able to enter a value is by selecting it from the list.

    Don't know if that matters to you or not.

    0 讨论(0)
  • 2020-11-30 23:48

    i just modify to code in my case & it's working

    selectFirst: true,
    change: function (event, ui) {
            if (ui.item == null){ 
             //here is null if entered value is not match in suggestion list
                $(this).val((ui.item ? ui.item.id : ""));
            }
        }
    

    you can try

    0 讨论(0)
提交回复
热议问题