dongzhouji4021 2018-10-04 15:01
浏览 42
已采纳

如何在自动完成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>
  • 写回答

1条回答 默认 最新

  • dongshang6790 2018-10-04 18:44
    关注

    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 :-)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度