0

I need an autocomplete feature that allows a user to only type/choose from the list of values from a DB table. I do not want them to be able to enter free text after the reason is selected.

I have referred to a similar posting jQuery UI AutoComplete: Only allow selected valued from suggested list1 but I have a different issue.

The challenge is the list of acceptable options have special characters, specifically "(" and ")". When I type an option with ( I can see it in the drop down but when I use the arrow keys to select it will go to the previous option.

The array of acceptable options from PHP are accessed in javascript using

var validOptions = <?php echo json_encode($validOptionsArray); ?>;

The javascript is

previousValue = "";

$('.getValidOptions').autocomplete({
    source: validOptions,   

}).keyup(function() {
    var isValid = false; 
    for (i in validOptions) {
       if (validOptions[i].toLowerCase().match(this.value.toLowerCase())) {
            isValid = true;
        }
    }
    if (!isValid) {
        this.value = previousValue;
    } else {
        previousValue = this.value;
    }
});

I understand how this is happening. If I remove the line

this.value = previousValue;

it will allow me to select the option with ( but then the user can continue typing.

However, I want to keep this line as it prevents the user from adding text to the dropdown.

I can use the mouse to select the option but I get an error in the console

Uncaught SyntaxError: Invalid regular expression: /(/

So it seems the issue is related to keyup function

I have tried (1) charset="utf-8" and (2) regular expression such as

(this.value).replace(/([.*+?^=!${}()|[\]\/\\])/g, '\\$1');

Any thoughts on how to fix this?

Thanks.


The data in the json_encode($validOptionsArray) is

Array
(
    [0] => NI: New Member
    [1] => NI: New Member (referred from current member)
    [2] => RI: Returning Member
    [3] => RI: Returning Member (with conditions)
    [4] => XI: Exclusive member (full/all access)
)
Gman
  • 35
  • 8

1 Answers1

0

I decided to go with jQuery inputToken http://loopj.com/jquery-tokeninput/

It is easy to implement and allows the user to only select the available options and not edit them. Maybe others will find this useful.

Gman
  • 35
  • 8