2

I have a select box phone numbers in us format, i need to search the values with or without formatting using select 2.

For example.

Select box values includes

(111) 222-3333

(222) 333-4444

(444) 555-6666

Now my select 2 search only works if I search number in correct format (111) 222-3333, I need to get results even if I search for 1112223333.

<select class="js-example-basic-single" id="list" name="inventory" placeholder="Select">
   <option value="1">(111) 222-3333</option>
   <option value="2">(222) 333-4444</option>
   <option value="3">(444) 555-6666</option>
</select>

<script>
  $('.js-example-basic-single').select2();
</script>

Thanks

1 Answer 1

2

You can use the search functionality below to achieve the intended result:

<!DOCTYPE html>
<meta charset="utf-8">

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.css" rel="stylesheet" />
    <style>
    </style>
</head>

<body>

    <select class="js-example-basic-single" id="list" name="inventory" placeholder="Select">
        <option value="1">(111) 222-3333</option>
        <option value="2">(222) 333-4444</option>
        <option value="3">(444) 555-6666</option>
    </select>
    <script>
        function ignoreSpecialCharAndWhitespace(params, data) {
            params.term = params.term || '';

            term = params.term.toUpperCase().replace(/ /g, String.fromCharCode(160));
            term = term.replace(/[^a-zA-Z0-9]/g, '');
            text1 = data.text.toUpperCase();
            text1 = text1.replace(/[^a-zA-Z0-9]/g, '');

            if (text1.indexOf(term) > -1 ) {
                return data;
            }
            return false;
        }

        $('.js-example-basic-single').select2({
            matcher: function(params, data) {    
                return ignoreSpecialCharAndWhitespace(params, data);
            }
        });
    </script>
</body>

</html>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.