javascript – 自动完成在自动完成窗口中显示相关数据

前端之家收集整理的这篇文章主要介绍了javascript – 自动完成在自动完成窗口中显示相关数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有3个输入字段,1个用于数据类型,其他2个是相关的.
当我按下数据类型字段中的按钮时,我想显示像这个

desired

自动完成窗口

而不是这个

undesired

选择之后应该看起来像这样

result

HTML

JS

  1. $(document).on('focus','.type',function(){
  2. type = $(this).data('type');
  3. if(type =='vehicle' )autoTypeNo = 1;
  4. $(this).autocomplete({
  5. source: function( request,response ) {
  6. $.ajax({
  7. url : 'autocomplete.PHP',dataType: "json",method: 'post',data: {
  8. name_startsWith: request.term,type: type
  9. },success: function( data ) {
  10. response( $.map( data,function( item ) {
  11. var code = item.split("|");
  12. return {
  13. label: code[autoTypeNo],value: code[autoTypeNo],data : item
  14. }
  15. }));
  16. }
  17. });
  18. },autoFocus: true,minLength: 0,select: function( event,ui ) {
  19. var names = ui.item.data.split("|");
  20. id_arr = $(this).attr('id');
  21. id = id_arr.split("_");
  22. $('#no_'+id[1]).val(names[0]);
  23. $('#vehicle_'+id[1]).val(names[1]);
  24. $('#type_'+id[1]).val(names[2]);
  25. }
  26. });
  27. });
最佳答案
您需要更改autocomplete.PHP然后返回所有3个值,您可以在json数组中轻松执行此操作http://php.net/manual/en/function.json-encode.php然后读取jquery脚本中的值.

这是您更新的JS脚本

  1. $(document).on('focus',function( item ) {
  2. //var code = item.split("|");
  3. return {
  4. label: item.no + '-' + item.vehicle + '-' + item.type,value: item.vehicle,ui ) {
  5. //var names = ui.item.data.split("|");
  6. id_arr = $(this).attr('id');
  7. id = id_arr.split("_");
  8. $('#no_'+id[1]).val(ui.item.data.no);
  9. $('#vehicle_'+id[1]).val(ui.item.data.vehicle);
  10. $('#type_'+id[1]).val(ui.item.data.type);
  11. }
  12. });
  13. });

猜你在找的jQuery相关文章