如何在自动完成jquery ui中创造价值?

如何在自动完成jquery ui中创造价值?

问题描述:

In my user table I have id_user and name. My autocomplete searches only by name. I need id_user to input into the database. Usually, we can write id_user as a value attribute in the input tag. This is the code :

Controller :

function get_autocomplete(){
        if (isset($_GET['term'])) {
            $result = $this->User_model->search($_GET['term']);
            if (count($result) > 0) {
            foreach ($result as $row)
                $arr_result[] = $row->name;
                echo json_encode($arr_result);
            }
        }
    }

Model :

function search($name){
        $this->db->like('name', $name , 'both');
        $this->db->order_by('name', 'ASC');
        $this->db->limit(10);
        return $this->db->get('user')->result();
    }

View :

<input type="text" id="name" placeholder="Name" name="id_user">
<script type="text/javascript">
        $(document).ready(function(){
            $( "#name" ).autocomplete({
              source: "<?php echo site_url('admin/user/get_autocomplete/?');?>"
            });
        });
    </script>

在我的 user code>表中,我有 id_user code>和名称代码>。 我的自动填充功能仅按名称进行搜索。 我需要 id_user code>来输入数据库。 通常,我们可以在输入标记中将 id_user code>写为值属性。 这是代码: p>

控制器: p>

  function get_autocomplete(){
 if(isset($ _ GET ['term']  )){
 $ result = $ this-&gt; User_model-&gt; search($ _ GET ['term']); 
 if(count($ result)&gt; 0){
 foreach($ result as $  row)
 $ arr_result [] = $ row-&gt; name; 
 echo json_encode($ arr_result); 
} 
} 
} 
  code>  pre> 
 
 

型号: p>

 功能搜索($ name){
 $ this-&gt; db-&gt; like('name',$ name,'both'); \  n $ this-&gt; db-&gt; order_by('name','ASC'); 
 $ this-&gt; db-&gt; limit(10); 
 return $ this-&gt; db-&gt; get  ('user') - &gt; result(); 
} 
  code>  pre> 
 
 

查看: p>

 &lt;  input type =“text”id =“name”placeholder =“Name”name =“id_user”&gt; 
&lt; script type =“text / javascript”&gt; 
 $(document).ready(function(){\  n $(“#name”)。autocomplete({
 source:“&lt;?php echo site_url('admin / user / get_autocomplete /?  ');?&gt;“
}); 
}); 
&lt; / script&gt; 
  code>  pre> 
  div>

You can fill the autocomplete options with Label/Value pairs. So the options show the label (e.g. username) and when the user selects one option the value (e.g. id_user) is written to the input field (= the value and is therefor it's displayed in the input field)

So your php code should return a JSON array with label/value pairs

foreach ($result as $row)
    $arr_result[] = array('label' => $row->name, 'value' => $row->id_user);
}
echo json_encode($arr_result);

Please take a look at my jsfiddle example - it shows the autocomplete with static data https://jsfiddle.net/jf7ynxwz/3/

If you don't like the user_id to be written into the input (visible) it's a little bit more complicated. Have a look into the documentation and maybe set the value as an data-html attribute of the input after selection :-)