Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you restrict entering invalid keystrokes with jQuery UI autocomplete combobox?

When using the jQuery UI autocomplete combobox, I would thought there would be an option to force only a valid key entry based on the list. Is there any way to not allow invalid keys, so you can only enter valid items in the list? Also, is there a way to set a default value of the combobox?

If my list has (C#, Java, Python)

I can start typing "abcds . ." and it lets me type it in. I want only valid entries to be allowed.

like image 476
leora Avatar asked Apr 25 '10 15:04

leora


2 Answers

UPDATED 2

Tested on
Internet Explorer 6 and later
Chrome
Firefox
Opera

Demo: http://so.lucafilosofi.com/can-you-restrict-entering-invalid-keystrokes-with-jquery-ui-autocomplete-combobox

Core JavaScript code:

    var Tags = ['csharp', 'java', 'python' ];

    $("#autocomplete").keypress(function(event) {
        //Firefox workaround..
        if (!event.which &&
            ((event.charCode || event.charCode === 0) ? event.charCode: event.keyCode)) {

            event.which = event.charCode || event.keyCode;
        }
        var charCode = String.fromCharCode(event.which).toLowerCase();
        var search_val = this.value + charCode;
        var x = search_val.length - 1;
        var match;
        for (var i = 0; i < Tags.length; i++) {
            if (charCode == Tags[i][x] && Tags[i].indexOf(search_val) != -1) {
                match = true;
            }
        }
        //Backspace functionality added!
        if (!match && event.which != 8 ) {
            event.preventDefault();
        }
    });

NOTE:

  1. force only valid key entry based on the list;
  2. set a default value;
  3. lightweight implementation ;-)

Let me know!

like image 176
18 revs, 3 users 85% Avatar answered Sep 24 '22 14:09

18 revs, 3 users 85%


After setting up your autocomplete, use this code to prevent the space character and equals character (ASCII code 32 and 61). And to set a default;

     $("#myautocompletectrl").keypress(function (e) {
        if (e.which == 32 | e.which == 61) {
          e.preventDefault();
        }
     }).val('mydefaultvalue');

It acts like the key was never pressed (as you say you wanted).

Tested on Firefox 3.63 and jQuery UI 1.8 Autocomplete.

Also, if you find that you additionally want to implement the mustMatch functionality in the jQuery UI 1.8 autocomplete, then look here: How to implement "mustMatch" and "selectFirst" in jQuery UI Autocomplete?

EDIT: I see you've already read and commented on my post.... :)

like image 24
GordonB Avatar answered Sep 26 '22 14:09

GordonB