почему динамические значения не заполняются в поле со списком автозаполнения? - PullRequest
0 голосов
/ 03 октября 2018

Я привел много примеров из вопросов jquery и StackOverflow.Но нигде не приведен пример для добавления значений в базу данных в поле со списком автозаполнения.Вот почему я открыл этот вопрос здесь.

Пожалуйста, посоветуйте, почему значения массива не заполняются в поле со списком автозаполнения?Вот мой пример кодирования

   (function($) {
$.widget( "custom.combobox", {
    _create: function() {
      this.wrapper = $( "<span>" )
        .addClass( "custom-combobox" )
        .insertAfter( this.element );

      this.element.hide();
      this._createAutocomplete();
      this._createShowAllButton();
    },

    _createAutocomplete: function() {
      var selected = this.element.children( ":selected" ),
        value = selected.val() ? selected.text() : "";

      this.input = $( "<input>" )
        .appendTo( this.wrapper )
        .val( value )
        .attr( "title", "" )
        .addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
        .autocomplete({
          delay: 0,
          minLength: 3,
          source: $.proxy( this, "_source" )
        })
        .tooltip({
          tooltipClass: "ui-state-highlight"
        });

      this._on( this.input, {
        autocompleteselect: function( event, ui ) {
          ui.item.option.selected = true;
          this._trigger( "select", event, {
            item: ui.item.option
          });
        },

        autocompletechange: "_removeIfInvalid"
      });
    },

    _createShowAllButton: function() {
      var input = this.input,
        wasOpen = false;

      $( "<a>" )
        .attr( "tabIndex", -1 )
        .attr( "title", "Show All Items" )
        .tooltip()
        .appendTo( this.wrapper )
        .button({
          icons: {
            primary: "ui-icon-triangle-1-s"
          },
          text: false
        })
        .removeClass( "ui-corner-all" )
        .addClass( "custom-combobox-toggle ui-corner-right" )
        .mousedown(function() {
          wasOpen = input.autocomplete( "widget" ).is( ":visible" );
        })
        .click(function() {
          input.focus();

          // Close if already visible
          if ( wasOpen ) {
            return;
          }

          // Pass empty string as value to search for, displaying all results
          input.autocomplete( "search", "" );
        });
    },

    _source: function( request, response ) {

     var autocompleteList = [];
     autocompleteList=['test1','test2','test3','test4'];
     if(autocompleteList.length>0){
      console.log(autocompleteList) ;
       for(var j=0;j<autocompleteList.length;j++){

        return {
          label:autocompleteList[j],
          value:autocompleteList[j],
          option:this
       }
      }

     }

    },

    _removeIfInvalid: function( event, ui ) {

      // Selected an item, nothing to do
      if ( ui.item ) {
        return;
      }

      // Search for a match (case-insensitive)
      var value = this.input.val(),
        valueLowerCase = value.toLowerCase(),
        valid = false;
      this.element.children( "option" ).each(function() {
        if ( $( this ).text().toLowerCase() === valueLowerCase ) {
          this.selected = valid = true;
          return false;
        }
      });

      // Found a match, nothing to do
      if ( valid ) {
        return;
      }

      // Remove invalid value
      this.input
        .val( "" )
        .attr( "title", value + " didn't match any item" )
        .tooltip( "open" );
      this.element.val( "" );
      this._delay(function() {
        this.input.tooltip( "close" ).attr( "title", "" );
      }, 2500 );
      this.input.data( "ui-autocomplete" ).term = "";
    },

    _destroy: function() {
      this.wrapper.remove();
      this.element.show();
    }
  });
  })(jQuery);

  $(function() {
    $("#combobox").combobox({

    });

    //$("#combobox").closest(".ui-widget").find("input, button").prop("disabled", true);
});

HTML

 <div class="ui-widget">
  <select id="combobox">

</select>
</div>

Ответы [ 3 ]

0 голосов
/ 06 октября 2018

Я бы посоветовал что-то вроде:

$(function() {
  $("#combobox").combobox({
    source: function(req, resp) {
      var autocompleteList = [];
      var results = [];
      session.run('MATCH (n) RETURN n.name').then(function(result) {
        $.each(result.records, function(k, r) {
          autocompleteList.push(r._fields[0]);
        });
      });
      if (req.term.length) {
        results = $.ui.autocomplete.filter(autocompleteList, req.term);
      } else {
        results = autocompleteList;
      }
      resp(results);
    },
    select: function(event, ui) {
      $('#log').text('selected ' + $("#combobox").val());
    }
  });
});

Это перезапустит обратный вызов source и выполнит необходимые действия для сбора полного списка, а если пользователь что-то набрал, уменьшите список доте элементы, которые соответствуют тому, что было напечатано.

Так как этот комбинированный список является пользовательским, я не думаю, что существует обратный вызов selected.Автозаполнение использует select обратный вызов.Так что я бы попробовал это в первую очередь.В противном случае вы можете создать обратный вызов selected в своем коде.

В противном случае соберите свой список перед инициализацией ComboBox.Надеюсь, это поможет.

0 голосов
/ 09 октября 2018

изменить только выбранные элементы списка;изменение выпадающего списка выбирает элементы автоматически обновляет автозаполнение

    $('#combobox').empty();
    for (var i = start_index; i < start_index + 4; i++) {
        $('#combobox').append(' <option value=test"' + i + '">test' + i + '</option>');
    }

 $( function() {
   
   var autocompleteList = [];
     autocompleteList=['test1','test2','test3','test4'];
      
   for(var i=0; i<autocompleteList.length; i++){
     
             $('#combobox').append(' <option value="' + autocompleteList[i] + '">' + autocompleteList[i] + '</option>');

   }
   
    $.widget( "custom.combobox", {
      _create: function() {
        this.wrapper = $( "<span>" )
          .addClass( "custom-combobox" )
          .insertAfter( this.element );
 
        this.element.hide();
        this._createAutocomplete();
        this._createShowAllButton();
      },
 
      _createAutocomplete: function() {
        var selected = this.element.children( ":selected" ),
          value = selected.val() ? selected.text() : "";
 
        this.input = $( "<input>" )
          .appendTo( this.wrapper )
          .val( value )
          .attr( "title", "" )
          .addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
          .autocomplete({
            delay: 0,
            minLength: 0,
            source: $.proxy( this, "_source" )
          })
          .tooltip({
            classes: {
              "ui-tooltip": "ui-state-highlight"
            }
          });
 
        this._on( this.input, {
          autocompleteselect: function( event, ui ) {
            ui.item.option.selected = true;
            this._trigger( "select", event, {
              item: ui.item.option
            });
          },
 
          autocompletechange: "_removeIfInvalid"
        });
      },
 
      _createShowAllButton: function() {
        var input = this.input,
          wasOpen = false;
 
        $( "<a>" )
          .attr( "tabIndex", -1 )
          .attr( "title", "Show All Items" )
          .tooltip()
          .appendTo( this.wrapper )
          .button({
            icons: {
              primary: "ui-icon-triangle-1-s"
            },
            text: false
          })
          .removeClass( "ui-corner-all" )
          .addClass( "custom-combobox-toggle ui-corner-right" )
          .on( "mousedown", function() {
            wasOpen = input.autocomplete( "widget" ).is( ":visible" );
          })
          .on( "click", function() {
            input.trigger( "focus" );
 
            // Close if already visible
            if ( wasOpen ) {
              return;
            }
 
            // Pass empty string as value to search for, displaying all results
            input.autocomplete( "search", "" );
          });
      },
 
      _source: function( request, response ) {
        var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
        response( this.element.children( "option" ).map(function() {
          var text = $( this ).text();
          if ( this.value && ( !request.term || matcher.test(text) ) )
            return {
              label: text,
              value: text,
              option: this
            };
        }) );
      },
 
      _removeIfInvalid: function( event, ui ) {
 
        // Selected an item, nothing to do
        if ( ui.item ) {
          return;
        }
 
        // Search for a match (case-insensitive)
        var value = this.input.val(),
          valueLowerCase = value.toLowerCase(),
          valid = false;
        this.element.children( "option" ).each(function() {
          if ( $( this ).text().toLowerCase() === valueLowerCase ) {
            this.selected = valid = true;
            return false;
          }
        });
 
        // Found a match, nothing to do
        if ( valid ) {
          return;
        }
 
        // Remove invalid value
        this.input
          .val( "" )
          .attr( "title", value + " didn't match any item" )
          .tooltip( "open" );
        this.element.val( "" );
        this._delay(function() {
          this.input.tooltip( "close" ).attr( "title", "" );
        }, 2500 );
        this.input.autocomplete( "instance" ).term = "";
      },
 
      _destroy: function() {
        this.wrapper.remove();
        this.element.show();
      }
    });
 
    $( "#combobox" ).combobox();
      $('.custom-combobox-input').val('');
   var start_index=5;
    $( "#btnUpdate" ).on( "click", function() {
      $('#combobox').empty();
    for (var i = start_index; i < start_index + 4; i++) {
        $('#combobox').append(' <option value=test"' + i + '">test' + i + '</option>');
    }
      
      $('.custom-combobox-input').val('');
      start_index+=5;
    });
  } );
.custom-combobox-toggle {
     padding: 13px!important;
    margin-top: -2px!important;

}
.wrapper {
margin:30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.2/css/bootstrap.min.css"><link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<div class="wrapper">
<div class="ui-widget">
  <select id="combobox">

</select>
</div>
<br>
<input type="button" id="btnUpdate" class="btn btn-default" value="update" >
<div>
0 голосов
/ 03 октября 2018

Вот пример того, как это сделать, я только что создал массив для зацикливания, потому что у меня нет доступа к объекту сеанса.

var autocompleteList = [];

$(document).ready(function() {

	var records = ['test', 'test 2', 'test 3']

    records.forEach(function(record) {
      autocompleteList.push(record);
    });
    
    $( "#tags" ).autocomplete({
      source: autocompleteList
    });
    
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<script type="text/javascript" src="//code.jquery.com/jquery-2.2.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>
...