Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI Autocomplete: how to allow free text

I want to give possibility for user to add his own variant, not only one from suggested. But when I type something in the field and click ENTER my form submits.

Then I tried to catch keydown event for my field, but in this case I loose possibility to select a variant from suggestions using arrows and enter keys because 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;
    });
like image 778
DrSat Avatar asked Oct 05 '22 00:10

DrSat


1 Answers

If you want to prevent the form from submitting on enter you can use preventDefault:

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

For the autocomplete, be aware that triggering the 'autocompleteselect' event when the enter key is pressed will fire the 'autocompleteselect' handler twice when a user hits enter on a suggested item. To avoid this and the missing ui parameter, try adding users input as an suggested item using the response callback and setting autofocus to true.

Here is an example where the users input is added to the suggestions list when autocomplete has no matches.

$('#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;
});

Here is a jsfiddle example of the above.

Hope this helps.

like image 198
jfbalanc Avatar answered Oct 10 '22 02:10

jfbalanc