实现效果:
1.显示数据图片
2.支持中文搜索
代码实现:
Web前端代码:
<select name="member" id="member"> <script src="/theme/<?=T_D?>/assets/select2-master/dist/js/select2.js" type="text/javascript" ></script> <link href="/theme/<?=T_D?>/assets/select2-master/dist/css/select2.css" rel="stylesheet" type="text/css" />
JS代码:
1 //设置用户显示列表 2 $(function () { 3 //带图片 4 $("#member").select2({ 5 data:[<?php echo $show_user_list;?>], //json数据格式 6 templateResult: formatState 7 }); 8 }); 9 function formatState(state) { 10 if (!state.id) { return state.text; } 11 12 var $state = $( 13 "<span><img src=" + state.image + " style='height:40px; 40px'/>"+ state.element.text +"</span>" 14 ); 15 return $state; 16 }; 17 18 //选取用户数据后,将相关参数赋值给其他表单控件 19 $("#member").on('select2:select', function (evt) { 20 var user=evt['params']['data']; 21 $("#contacts").val(user['name']); 22 $('#phone').val(user['mobile']); 23 $('#birthday').val(user['birthday']); 24 $('#lang_hidden').val(user['lang']); 25 if(user['gender']==1) 26 { 27 $('#male').parent().attr("class","checked"); 28 $('#female').parent().removeClass("checked"); 29 $("#gender_hidden").val('1'); 30 }else 31 { 32 $('#female').parent().attr("class","checked"); 33 $('#male').parent().removeClass("checked"); 34 $("#gender_hidden").val('2'); 35 } 36 $("#userid_hidden").val(user['id']); 37 });
PHP后端代码:
//加载用户列表
1 $sql="select u.id,u.username,u.name,u.mobile,u.gender,u.birthday,u.avatar,tab1.end_time,h.default_lang from ( 2 select * from hc_chat where (data_from='3001' and param=1) or (data_from='7001' and param in (select id from hc_doctor where hospital_id=1))) 3 tab1 left JOIN hc_member u on u.id=tab1.member_id 4 LEFT JOIN hc_country h on h.id=u.country_id 5 order by end_time;"; 6 $user_list=$this->db->query($sql)->result_array(); 7 $show_user_list=''; 8 foreach($user_list as $item) 9 { 10 $show_user_list.="{id:"".$item['id'].""".",text:"".$item['username'].""".",image:"".$item['avatar']."",".''; 11 $show_user_list.="name:"".$item['name'].""".",mobile:"".$item['mobile'].""".",gender:"".$item['gender']."",".''; 12 $show_user_list.="birthday:"".$item['birthday'].""".",end_time:"".$item['end_time'].""".",lang:"".$item['default_lang'].""".'},'; 13 } 14 $show_user_list=substr($show_user_list,0,strlen($show_user_list)-1); 15 $show_user_list = str_replace(" ", "", $show_user_list); 16 $show_user_list = str_replace(" ", "", $show_user_list); 17 18 $data=array( 19 'position'=>$position, 20 'point'=>$point, 21 'user_list'=>$user_list, 22 'show_user_list'=> $show_user_list, 23 'doctor_list'=>$doctor_list 24 );
select2官网:http://select2.github.io/