官术网_书友最值得收藏!

Creating an autocomplete text input

On our web forms, there may be times when we want to have an autocomplete text field. This can be handy for populating common search terms or product names. Using the jQueryUI Autocomplete library along with Laravel, that becomes an easy task.

Getting ready

In this recipe, we'll be using the CDN versions of jQuery and jQueryUI; however, we could also download them and place them in our public/js directory, if we wanted to have them locally.

How to do it...

To complete this recipe, follow these steps:

  1. Create a route to hold our autocomplete form:
    Route::get('autocomplete', function()
    {
        return View::make('autocomplete');
    });
  2. Make a view in the app/views directory named autocomplete.php with our form's HTML and JavaScript:
    <!DOCTYPE html>
    <html>
        <head>
            <title>Laravel Autocomplete</title>
            <meta charset="utf-8">
            <link rel="stylesheet" />
            <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
            <script src="http://codeorigin.jquery.com/ui/1.10.2/jquery-ui.min.js"></script>
        </head>
        <body>
            <h2>Laravel Autocomplete</h2>
    
            <?= Form::open() ?>
            <?= Form::label('auto', 'Find a color: ') ?>
            <?= Form::text('auto', '', array('id' => 'auto'))?>
            <br>
            <?= Form::label('response', 'Our color key: ') ?>
            <?= Form::text('response', '', array('id' =>'response', 'disabled' => 'disabled')) ?>
            <?= Form::close() ?>
    
            <script type="text/javascript">
                $(function() {
                    $("#auto").autocomplete({
                        source: "getdata",
                        minLength: 1,
                        select: function( event, ui ) {
                            $('#response').val(ui.item.id);
                        }
                    });
                });
            </script>
        </body>
    </html>
  3. Create a route that will populate the data for the autocomplete field:
    Route::get('getdata', function()
    {
        $term = Str::lower(Input::get('term'));
        $data = array(
            'R' => 'Red',
            'O' => 'Orange',
            'Y' => 'Yellow',
            'G' => 'Green',
            'B' => 'Blue',
            'I' => 'Indigo',
            'V' => 'Violet',
        );
        $return_array = array();
    
        foreach ($data as $k => $v) {
            if (strpos(Str::lower($v), $term) !== FALSE) {
                $return_array[] = array('value' => $v, 'id' =>$k);
            }
        }
        return Response::json($return_array);
    });

How it works...

In our form, we're creating a text field to accept user input that will be used for the autocomplete. There's also a disabled text field that we can use to see the ID of the value that was selected. This can be useful if you have an ID for a particular value that's numeric, or otherwise not named in a standard way. In our example, we're using the first letter of the color as the ID.

As the user starts typing, autocomplete sends a GET request to the source that we added, using the word term in the query string. To process this, we create a route that gets the input, and convert it to lower-case. For our data, we're using a simple array of values but it would be fairly easy to add in a database query at this point. Our route checks the values in the array to see if there are any matches with the user input and, if so, adds the ID and value to the array we will return. Then, we output the array as JSON, for the autocomplete script.

Back on our form page, when the user selects a value, we add the ID to the disabled response field. Many times, this will be a hidden field, which we can then pass on when we submit the form.

There's more...

If we'd like to have our getdata route only accessible from our autocomplete form, or some other AJAX request, we could simply wrap the code in if (Request::ajax()) {} or create a filter that rejects any non-AJAX requests.

主站蜘蛛池模板: 大城县| 蛟河市| 乌拉特中旗| 增城市| 留坝县| 雅江县| 宁国市| 东宁县| 光山县| 东港市| 兴化市| 永吉县| 公安县| 清原| 莱阳市| 屏东市| 宝坻区| 莆田市| 宁晋县| 蓝山县| 含山县| 普安县| 巴林右旗| 西畴县| 社会| 南木林县| 梧州市| 哈尔滨市| 凤山县| 奈曼旗| 沂水县| 通山县| 淳化县| 平罗县| 区。| 玛曲县| 潼关县| 阳新县| 东丰县| 深水埗区| 黄梅县|