Autocomplete text field value select how to

Hello All,

I have a autocomplete text field in my user enter form but I’m unable to give it a value attribute. As of now I can populate the text field and make a selection but the selection is the user name and not the user value attribute.

How do I implement a the value attribute in my scrip so when the user makes a selection I can select the value instead of name. I thought about adding a select tag next to the text field but that would make it too busy.

Using: Laravel 10, Bootstrap 5, Jquery

**HTML script - works**
<div class="form-group">   
      <input type="text" class="form-control" id="nameSearch" 
                 name="nameSearch" placeholder="Name search" >
      <div class="dropdown">
              <div id="nameList"></div>
      </div>
</div> 

Laravel 10 controller - works

public function nameSearch(Request $request) { 
        if($request->ajax()) {                        
            $data=User::where('name', 'like', "%{$request-> 
                 nameSearch}%")->get(); 
            $nameList = '<ul class="dropdown-menu" style= 
                 "display:block; position:relative; width: 100%;">';
            foreach($data as $row) {
                $nameList .= '<li><a class="dropdown-item" href="">' . 
                      $row->name . '</a> '. $row->name .'</li>';                
            }
            $nameList .= '</ul>';           
            echo $nameList;
        }      
    }// END of SEARCH function

jQuery - works

$(document).ready(function() {    
    $('#nameSearch').on('keyup', function() {        
       var userValue = $(this).val(); 
       var _token = $('input[name="_token"]').val();      
       if(userValue != '') {
            $.ajax({
                type: "POST",        
                url: "/ticket/nameSearch",                
                data: {nameSearch: userValue ,  _token:_token},
                success: function (data) {                   
                    $('#nameList').fadeIn();  
                    $('#nameList').html(data);                 
                } //END of success
            });// END ajax
        }//END if statement
    });//END of keyup function
});// END of document ready

$(document).on('click','li', function() {
    $('#nameSearch').val($(this).text());
    $('#nameList').fadeOut();
});

Well presumably, you’d change that to something else. What that something else is, is kind of hard to tell without knowing where you’re putting the “value”, as none of the HTML generated provides a form object in your dropdown, only list items.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.