如何使用jquery自动完成组合框设置默认值?

前端之家收集整理的这篇文章主要介绍了如何使用jquery自动完成组合框设置默认值?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当使用 the jquery ui autocomplete组合框时,可以为组合框设置默认值吗?

解决方法

我试着用我自己的项目来解决这个问题.

我从您发布的页面中读取演示源代码.在生成自动完成组合框的jquery代码中,我添加了一行代码,当创建组合框时,它会从“select”元素中读取所选值.这样,您可以以编程方式设置默认值(就像您通常不使用自动完成组合框一样)

这是我添加的一行:

  1. input.val( $("#comboBox option:selected").text());

干净利落.它将输入的值设置为#comboBox中所选元素的文本值.当然,您需要更新id元素以匹配您的单个项目或页面.

这是在上下文中:

  1. (function($) {
  2. $.widget("ui.comboBox",{
  3. _create: function() {
  4. var self = this;
  5. var select = this.element.hide();
  6. var input = $("<input>")
  7. .insertAfter(select)
  8. .autocomplete({
  9. source: function(request,response) {
  10. var matcher = new RegExp(request.term,"i");
  11. response(select.children("option").map(function() {
  12. var text = $(this).text();
  13. if (this.value && (!request.term || matcher.test(text)))
  14. return {
  15. id: this.value,label: text.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(request.term) + ")(?![^<>]*>)(?![^&;]+;)","gi"),"<strong>$1</strong>"),value: text
  16. };
  17. }));
  18. },delay: 0,change: function(event,ui) {
  19. if (!ui.item) {
  20. // remove invalid value,as it didn't match anything
  21. $(this).val("");
  22. return false;
  23. }
  24. select.val(ui.item.id);
  25. self._trigger("selected",event,{
  26. item: select.find("[value='" + ui.item.id + "']")
  27. });
  28.  
  29. },minLength: 0
  30. })
  31. .addClass("ui-widget ui-widget-content ui-corner-left");
  32.  
  33.  
  34.  
  35. // This line added to set default value of the comboBox
  36. input.val( $("#comboBox option:selected").text());
  37.  
  38.  
  39.  
  40.  
  41.  
  42. $("<button>&nbsp;</button>")
  43. .attr("tabIndex",-1)
  44. .attr("title","Show All Items")
  45. .insertAfter(input)
  46. .button({
  47. icons: {
  48. primary: "ui-icon-triangle-1-s"
  49. },text: false
  50. }).removeClass("ui-corner-all")
  51. .addClass("ui-corner-right ui-button-icon")
  52. .click(function() {
  53. // close if already visible
  54. if (input.autocomplete("widget").is(":visible")) {
  55. input.autocomplete("close");
  56. return;
  57. }
  58. // pass empty string as value to search for,displaying all results
  59. input.autocomplete("search","");
  60. input.focus();
  61. });
  62. }
  63. });
  64.  
  65. })(jQuery);

猜你在找的jQuery相关文章