JQuery UI Autocomplete: how to enable free text

I want to allow the user to add their own version, and not just one of the proposed ones. But when I enter something into the field and press ENTER, my form is submitted.

Then I tried to catch the keydown event for my field, but in this case I have no way to select an option from the sentences using the arrows and enter the keys, because the ui parameter is undefined.

    $('#field_id').on('keydown', function(event) {
        if (event.keyCode == $.ui.keyCode.ENTER
            || event.keyCode == $.ui.keyCode.NUMPAD_ENTER)
        {

            $('#field_id').trigger('autocompleteselect');
        }
    });

    $('#field_id').autocomplete({
        source: [{"id":"20","value":"This is not mandatory decline reason"},{"id":"21","value":"You are have to be rejected"}]
        minLength: 0
    }).on('autocompleteselect', function(event, ui) {
        // if I click on suggestion using mouse - everything is ok
        // but not for ENTER-key choosing

        // I want something like that:
        if (ui.item) {
              id = ui.item.id;
              value = ui.item.value;
        } else {
              id = 'my_new_item';
              value = $(this).val();
        }
        return false;
    });
+5
source share
1 answer

If you want to prevent the form from being submitted when you enter, you can use preventDefault:

$(document).ready(function() {
  $(window).keydown(function(event){
    if(event.keyCode == 13) {
      event.preventDefault();
      return false;
    }
  });
});

, "autocompleteselect" "autocompleteselect" , . ui, , true.

, , .

$('#field_id').autocomplete({
    source: [{
        "id": "20",
            "value": "This is not mandatory decline reason"
    }, {
        "id": "21",
            "value": "You are have to be rejected"
    }],
    minLength: 0,
    autoFocus: true,
    response: function (event, ui) {

        if (ui.content.length == 0) {
            ui.content.push({
                label: "New Search value: " + $(this).val(),
                value: $(this).val(),
                id: 0
            });
        }
    }
}).on('autocompleteselect', function (event, ui) {
    id = ui.item.id;
    value = ui.item.value;

    return false;
});

jsfiddle.

, .

+4

All Articles