修复jQuery Autcomplete搜索框问题

时间:2019-05-09 12:25:20

标签: jquery ajax laravel

JQUERY代码

        $('#search').keyup(function() {
              check_search();
            });
            $('#search').focusout(function() {
              check_search();
            });
            function check_search() {
              var search = document.getElementById('search').value;
              if (search.length > 0) {
                $('#search').removeClass('border-danger');
                var _token = document.getElementById('_token').value;
                $.ajax({
                  url:"{{ route('pro.claim.autocomplete') }}",
                  method:"POST",
                  data:{search:search, _token:_token},
                  dataType:"json",
                  success:function(result){
                    $('#suggest_name').html(result);
                    $('#suggest_name').fadeIn();
                  }
                });
              } else {
                $('#suggest_name').fadeOut();
                $('#suggest_name').html('');
                $('#search').addClass('border-danger');
                $('#search').focus();
              }
            }
            // GET VALUE
            $(document).on('click','#select_name',function () {
              document.getElementById('search').value = $(this).attr('value');
              $('#suggest_name').fadeOut();
            });

HTML代码

        <div class="claim-searchbox">
                      <form id="search_business">
                        <div class="claim-searchInput">
                          <input type="hidden" name="_token" id="_token" value="{{ csrf_token() }}">
                          <input type="text" id="search" name="search" placeholder="Search business page">
                        </div>
                        <div class="suggest-name" id="suggest_name"></div>
                        <div class="claim-searchSubmit">
                          <input type="submit" value="Find Business">
                        </div>
                      </form>
                    </div>

LARAVEL代码

     // AUTOCOMPLETE
        public function autocomplete(Request $request)
        {
            $search = $request->search;
            $names = ProListing::where('name','like','%'.$search.'%')->get();
            $result = '<ul>';
            if (count($names) > 0) {
                foreach ($names as $name) {
                    $result .= '<li id="select_name" value="'.$name->name.'">'.$name->name.'</li>';
                }
            } else {
                $result .= '<li class="no-result">No Business Page Available</li>';
            }
            $result .= '</ul>';
            return response()->json($result);
        }

问题详细信息:

  • 一切正常。按要求淡入。但是,当我单击以将值设置为搜索框$('#suggest_name').fadeOut();而不是fadeOut时,它将再次显示,然后在第二次单击后,将其淡出。但我想在第一次单击后淡出div。在搜索框中获取值。

**帮我解决这个问题

0 个答案:

没有答案