2

Dispongo de un buscador inteligente, el cual he de capturar el valor en el momento que pierde el foco, pero no funciona correctamente al usar las funciones propias de jquery.

Dejo un fiddle con el código

y el código suelto

(function ($) {
  $.widget("ui.combobox", {
    _create: function () {

      var input, self = this,
        select = this.element.hide(),
        selected = select.children(":selected"),
        value = selected.val() ? selected.text() : "",
        wrapper = this.wrapper = $("<span>").addClass("ui-combobox").insertAfter(select);

      input = $("<input name=ComboId id=ComboId style='height:40px;'>").appendTo(wrapper).val(value).addClass("input form-control input-lg ui-state-default ui-combobox-input").autocomplete({
        delay: 0,
        minLength: 0,
        source: function (request, response) {

          if (request.term.length > 3) {
            var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");

            response(select.find("option").map(function () {
              var text = $(this).text();
              if (this.value && (!request.term || matcher.test(text))) return {
                label: text.replace(
                  new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(request.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"),
                value: text,
                option: this,
                category: $(this).closest("optgroup").attr("label")
              };
              //MK
              $('#test').attr('style', 'display: none;');
            }).get());
          }
        },
        select: function (event, ui) {
          ui.item.option.selected = true;
          self._trigger("selected", event, {
            item: ui.item.option
          });
        },
        change: function (event, ui) {
          if (!ui.item) {
            var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
              valid = false;
            select.children("option").each(function () {
              if ($(this).text().match(matcher)) {
                this.selected = valid = true;

                return false;
              }
            });
            if (!valid) {
              $('#test').attr('style', 'display: block;');
            }
          }
        }
      }).addClass("ui-widget ui-widget-content ui-corner-left");

      input.data("ui-autocomplete")._renderItem = function (ul, item) {
        return $("<li></li>").data("ui-autocomplete-item", item).append("<a>" + item.label + "</a>").appendTo(ul);
      };

      input.data("ui-autocomplete")._renderMenu = function (ul, items) {
        var self = this,
          currentCategory = "";

        //AÑADIDO
        //$('#loading').removeClass('hide');

        $.each(items, function (index, item) {
          if (item.category != currentCategory) {
            if (item.category) {
              ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>");
            }
            currentCategory = item.category;
          }
          self._renderItem(ul, item);
        });
        //AÑADIDO
        //$('#loading').addClass('hide');

      };

      $("<a>").attr("tabIndex", -1).attr("title", "Ver Todos").appendTo(wrapper).button({
        icons: {
          primary: "ui-icon-triangle-1-s"
        },
        text: false
      }).removeClass("ui-corner-all").addClass("ui-corner-right ui-combobox-toggle").click(function () {
        if (input.autocomplete("widget").is(":visible")) {
          input.autocomplete("close");
          return;
        }

        $(this).blur();

        input.autocomplete("search", "");
        input.focus();
      });
    },

    destroy: function () {
      this.wrapper.remove();
      this.element.show();
      $.Widget.prototype.destroy.call(this);
    }
  });
})(jQuery);		

$(function () {
  $("#Socios").combobox();
  $("#toggle").click(function () {
    $("#Socios").toggle();
  });
});
/*****************************/
/*****************************/
/*****************************/
/*****************************/
$("#Socios").focus(function () {
  alert("focus");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
    <input class="form-control input-lg" type="hidden" name="mostrar" id="mostrar" autocomplete="off">
    <select id="Socios" name="Socios" class="input form-control input-lg">
    <option value ="1" >111111111111</option>
    <option value ="2">222222222222</option>
    <option value ="3">33333333333</option>
    <option value ="4">4444444444444</option>
    <option value ="5">5555555555555</option>
    <option value ="6">6666666666666</option>
    <option value ="7">77777777777777</option>
    </select>

1 respuesta 1

2

Para conseguirlo podrías valerte de la función change que tiene el objeto autocomplete. Esta función puede recibir dos parámetros, uno de ellos es ui que es el objeto seleccionado del listado.

Si accedemos al value del item que tiene dicho objeto, estaríamos capturando el valor que necesitas.

(function ($) {
  $.widget("ui.combobox", {
    _create: function () {
      var input, self = this,
      select = this.element.hide(),
      selected = select.children(":selected"),
      value = selected.val() ? selected.text() : "",
      wrapper = this.wrapper = $("<span>").addClass("ui-combobox").insertAfter(select);
            
      input = $("<input name=ComboId id=ComboId style='height:40px;'>").appendTo(wrapper).val(value).addClass("input form-control input-lg ui-state-default ui-combobox-input").autocomplete({
        delay: 0,
        minLength: 0,
        source: function (request, response) {
          if (request.term.length > 3) {
            var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
            response(select.find("option").map(function () {
              var text = $(this).text();
              
              if (this.value && (!request.term || matcher.test(text))) return {
                label: text.replace(
                  new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(request.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"),
                value: text,
                option: this,
                category: $(this).closest("optgroup").attr("label")
              };
              
              //MK
              $('#test').attr('style', 'display: none;');
            }).get());
          }
        },
        select: function (event, ui) {
          ui.item.option.selected = true;
          self._trigger("selected", event, {
            item: ui.item.option
          });
        },
        change: function (event, ui) {
          alert('Valor seleccionado: ' + ui.item.value);
          
          if (!ui.item) {
            var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
            valid = false;
            select.children("option").each(function () {
              if ($(this).text().match(matcher)) {
                this.selected = valid = true;
                return false;
              }
            });
            
            if (!valid) {
              $('#test').attr('style', 'display: block;');
            }
          }
        }
      }).addClass("ui-widget ui-widget-content ui-corner-left");

      input.data("ui-autocomplete")._renderItem = function (ul, item) {
        return $("<li></li>").data("ui-autocomplete-item", item).append("<a>" + item.label + "</a>").appendTo(ul);
      };

      input.data("ui-autocomplete")._renderMenu = function (ul, items) {
        var self = this,
        currentCategory = "";

        //AÑADIDO
        //$('#loading').removeClass('hide');

        $.each(items, function (index, item) {
          if (item.category != currentCategory) {
            if (item.category) {
              ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>");
            }
            
            currentCategory = item.category;
            
          }
          
          self._renderItem(ul, item);
        });
        //AÑADIDO
        //$('#loading').addClass('hide');
      };

      $("<a>").attr("tabIndex", -1).attr("title", "Ver Todos").appendTo(wrapper).button({
        icons: {
          primary: "ui-icon-triangle-1-s"
        },
        text: false
      }).removeClass("ui-corner-all").addClass("ui-corner-right ui-combobox-toggle").click(function () {
        if (input.autocomplete("widget").is(":visible")) {
          input.autocomplete("close");
          return;
        }

        $(this).blur();
        input.autocomplete("search", "");
        input.focus();
      });
    },
    destroy: function () {
      this.wrapper.remove();
      this.element.show();
      $.Widget.prototype.destroy.call(this);
    }
  });
})(jQuery);		

$(function () {
  $("#Socios").combobox();
  $("#toggle").click(function () {
    $("#Socios").toggle();
  });
});

/*****************************/
/*****************************/
/*****************************/
/*****************************/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<input class="form-control input-lg" type="hidden" name="mostrar" id="mostrar" autocomplete="off">

<select id="Socios" name="Socios" class="input form-control input-lg">
  <option value ="1" >111111111111</option>
  <option value ="2">222222222222</option>
  <option value ="3">33333333333</option>
  <option value ="4">4444444444444</option>
  <option value ="5">5555555555555</option>
  <option value ="6">6666666666666</option>
  <option value ="7">77777777777777</option>
</select>

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.