Domanda

Sto usando il plugin scelto.js http://harvesthq.github.com/chosen/ con jQuery per consentire all'utente di selezionare più opzioni da una selezione. Tuttavia, ora voglio essere in grado di lasciarli creare Valori che non sono già presenti - qualche idea su come procedere?

EDIT: qualcosa di simile alla barra di selezione/creazione dei tag di So SO sarebbe vicino a quello che sto cercando

Preferibilmente senza cambiare o modificare il plug -in, ma lo farà se necessario.

Il codice: html:

<p>Select something</p>
<select name="theSelect[]" multiple="multiple">
    <option value="First Option">First Option</option>
    <option value="Second Option">Second Option</option>
</select>

JavaScript:

$(function(){
    $('select').chosen();
});

Quindi, se un utente dovesse digitare "terza opzione", vorrei aggiungerlo all'elenco e farlo selezionare. Il valore e il nome visualizzato sono / saranno gli stessi, quindi non è una preoccupazione

È stato utile?

Soluzione

Secondo la documentazione puoi provare a fare qualcosa del genere:

$('select').append('<option>test</option>');
$('select').trigger('liszt:updated');

Come ha affermato Tony nei commenti qui sotto:

"A partire dalla versione 1.0 che il trigger è ora" scelto: aggiornato ". Vedi Harvesthq.Github.io/chosen/#change-update-events"

Altri suggerimenti

Mi sono imbattuto in questo cercando le stesse idee. Sembra che sia una richiesta di funzionalità piuttosto popolare e un paio di forcelle l'hanno implementata. Sembra che verrà fuso nel ramo principale abbastanza presto.

+1 per questo particolare tiro che ha funzionato un fascino:https://github.com/harvesthq/chosen/pull/166

Puoi visualizzare la forcella di Koenpunt qui: https://github.com/koenpunt/cosen

Ecco un modo semplice in cui l'ho fatto:

$(".search-field").find("input").live( "keydown", function (evt) {
    var stroke;
    stroke = (_ref = evt.which) != null ? _ref : evt.keyCode;
    if (stroke == 9) { // 9 = tab key
        $('#tags').append('<option value="' + $(this).val() + '" selected="selected">' + $(this).val() + '</option>');
        $('#tags').trigger('chosen:updated');
    }
});

Stavo solo cercando di risolvere lo stesso problema. Ho finito per modificare un po 'il codice sorgente. Ecco la nuova funzione KeyUp_Checker. Dai un'occhiata al caso 13:

AbstractChosen.prototype.keyup_checker = function(evt) {
  var stroke, _ref;
  stroke = (_ref = evt.which) != null ? _ref : evt.keyCode;
  this.search_field_scale();
  switch (stroke) {
    case 8:
      if (this.is_multiple && this.backstroke_length < 1 && this.choices > 0) {
        return this.keydown_backstroke();
      } else if (!this.pending_backstroke) {
        this.result_clear_highlight();
        return this.results_search();
      }
      break;
    case 13:
      evt.preventDefault();
      if (this.results_showing) {
        if (!this.is_multiple || this.result_highlight) {
          return this.result_select(evt);
        }  

        $(this.form_field).append('<option>' + $(evt.target).val() + '</option>');
        $(this.form_field).trigger('liszt:updated');
        this.result_highlight = this.search_results.find('li.active-result').last();
        return this.result_select(evt);
      } 
      break;
    case 27:
      if (this.results_showing) this.results_hide();
      return true;
    case 9:
    case 38:
    case 40:
    case 16:
    case 91:
    case 17:
      break;
    default:
      return this.results_search();
  }
};

So che questa non è la risposta, ma una soluzione alternativa.

Stavo cercando la parte aggiunta al volo e lo ho trovato http://ivaynberg.github.com/select2/#tags Fornisce la stessa cosa di scelta + altre cose come "tagging".

Potresti semplicemente allegare un evento alla casella di testo di input per ascoltare un particolare codice personaggio. Successivamente aggiungi l'opzione e attiva l'aggiornamento sul discesa.

 var dropDown = $('select.chosen');
 dropDown.parent().find('.chzn-container .chzn-search input[type=text]').keydown( function (evt) {
           var stroke, _ref, target, list;
           // get keycode
           stroke = (_ref = evt.which) != null ? _ref : evt.keyCode;
           target = $(evt.target);               
           // get the list of current options
           list = target.parents('.chzn-container').find('.chzn-choices li.search-choice > span').map(function () { return $(this).text(); }).get();
           if (stroke === 9 || stroke === 13) {
              var value = $.trim(target.val());
              // if the option does not exists
              if ($.inArray(value,list) < 0) {
                 var option = $('<option>');
                 option.text(value).val(value).appendTo(dropDown);
                 option.attr('selected','selected');
                 // add the option and set as selected
              }
              // trigger the update event
              dropDown.trigger("liszt:updated");
              return true;
           }
        });

Un aggiornamento alla risposta di Leogdion che funziona con le versioni successive di scelta:

        var dropDown = $('#select_chosen');
        // Make the chosen drop-down dynamic. If a given option is not in the list, the user can still add it
        dropDown.parent().find('.chosen-container .search-field input[type=text]').keydown( 
            function (evt) {
               var stroke, _ref, target, list;
               // get keycode
               stroke = (_ref = evt.which) != null ? _ref : evt.keyCode;
               // If enter or tab key
               if (stroke === 9 || stroke === 13) {
                   target = $(evt.target);               
                   // get the list of current options
                   chosenList = target.parents('.chosen-container').find('.chosen-choices li.search-choice > span').map(function () { return $(this).text(); }).get();
                   // get the list of matches from the existing drop-down
                   matchList = target.parents('.chosen-container').find('.chosen-results li').map(function () { return $(this).text(); }).get();
                   // highlighted option
                   highlightedList = target.parents('.chosen-container').find('.chosen-results li.highlighted').map(function () { return $(this).text(); }).get();
                   // Get the value which the user has typed in
                   var newString = $.trim(target.val());
                   // if the option does not exists, and the text doesn't exactly match an existing option, and there is not an option highlighted in the list
                   if ($.inArray(newString,matchList) < 0 && $.inArray(newString,chosenList) < 0 && highlightedList.length == 0) {
                     // Create a new option and add it to the list (but don't make it selected)
                     var newOption = '<option value="' + newString + '">' + newString + '</option>';
                     $("#select").prepend(newOption);
                     // trigger the update event
                     $("#select").trigger("chosen:updated");
                     // tell chosen to close the list box
                     $("#select").trigger("chosen:close");
                     return true;
                  } 
                  // otherwise, just let the event bubble up
                  return true;
               }
            }
        )

Ho aggiornato il codice dal 3NOCHROOT ancora una volta. Ora ho un solo selettore per trovare l'ingresso multiseletto.

$(document).ready(function() {
$(".js-choicelist").chosen({
    //config comes here
}).parent().find('.chosen-container .search-field input[type=text]').keydown(
    function (evt) {
        var stroke, _ref, target, list;
        // get keycode
        stroke = (_ref = evt.which) != null ? _ref : evt.keyCode;
        // If enter or tab key
        if (stroke === 9 || stroke === 13) {
            target = $(evt.target);
            // get the list of current options
            chosenList = target.parents('.chosen-container').find('.chosen-choices li.search-choice > span').map(function () { return $(this).text(); }).get();
            // get the list of matches from the existing drop-down
            matchList = target.parents('.chosen-container').find('.chosen-results li').map(function () { return $(this).text(); }).get();
            // highlighted option
            highlightedList = target.parents('.chosen-container').find('.chosen-results li.highlighted').map(function () { return $(this).text(); }).get();
            // Get the value which the user has typed in
            var newString = $.trim(target.val());
            // if the option does not exists, and the text doesn't exactly match an existing option, and there is not an option highlighted in the list
            if ($.inArray(newString,matchList) < 0 && $.inArray(newString,chosenList) < 0 && highlightedList.length == 0) {
                // Create a new option and add it to the list (but don't make it selected)
                var newOption = '<option value="' + newString + '">' + newString + '</option>';
                var choiceSelect = target.parents('.select-multiple').find('select');
                choiceSelect.prepend(newOption);
                // trigger the update event
                choiceSelect.trigger("chosen:updated");
                // tell chosen to close the list box
                choiceSelect.trigger("chosen:close");
                return true;
            }
            // otherwise, just let the event bubble up
            return true;
        }
    }
)

})

Aggiornamento della risposta Leogdion per più selezioni (GIST)

  $(".chosen-select-with-add-new").chosen({
    no_results_text: "Click Enter or Tab to add new option",
    width: '100%'
  }).parent().find('.chosen-container .search-field input[type=text]').keydown(function (evt) {
    // get keycode
    const stroke = evt.which != null ? evt.which : evt.keyCode;
    // If enter or tab key
    if (stroke === 9 || stroke === 13) {
      const target = $(evt.target);
      // get the list of current options
      const chosenList = target.parents('.chosen-container').find('.chosen-choices li.search-choice > span').map(function () { return $(this).text(); }).get();
      // get the list of matches from the existing drop-down
      const matchList = target.parents('.chosen-container').find('.chosen-results li').map(function () { return $(this).text(); }).get();
      // highlighted option
      const highlightedList = target.parents('.chosen-container').find('.chosen-results li.highlighted').map(function () { return $(this).text(); }).get();
      // Get the value which the user has typed in
      const newString = $.trim(target.val());
      // if the option does not exists, and the text doesn't exactly match an existing option, and there is not an option highlighted in the list

      if ($.inArray(newString, matchList) < 0 && $.inArray(newString,chosenList) < 0 && highlightedList.length == 0) {
        // Create a new option and add it to the list (but don't make it selected)
        const newOption = '<option value="' + newString + '" selected="selected">' + newString + '</option>';
        const choiceSelect = target.parents('.chosen-container').siblings('.chosen-select-with-add-new');
        choiceSelect.append(newOption);
        // trigger the update event
        choiceSelect.trigger("chosen:updated");
        // tell chosen to close the list box
        choiceSelect.trigger("chosen:close");
        return true;
      }
      // otherwise, just let the event bubble up
      return true;
    }
  })

Esempio di utilizzo sui binari (slim)

  .tag-list
    label.control-label.h5 Tag list
    = select_tag :tag_list, options_for_select(ActsAsTaggableOn::Tag.order('taggings_count desc').pluck(:name), @publication.tags.map(&:name)), multiple: true, data: { placeholder: 'north, east, south, west' }, class: 'chosen-select-with-add-new'

Ho provato diverse soluzioni fornite qui e altrove, tuttavia nessuna ha funzionato in prescelto.js 1.8.5 (jQuery: 3.3.1) e così ho finito con quanto segue poiché non volevo usare una forcella che potrebbe non essere sempre attivo -Dada al ramo principale:

Nel caso che potrei non voler nessuno .chosen-select Per consentire nuovi valori, ho aggiunto una nuova classe .chosen-newValuesAllowed. Ho impostato un gestore di eventi in questa classe dove Ctrl + i Aggiunge il nuovo valore se non è ancora presente. L'attenzione sul campo di input non si perde dopo. Nel mio esempio, controllo l'internhtml del poiché @Value contiene effettivamente ID del database e quindi il nuovo valore, che è una stringa nel mio esempio che verrebbe elaborata dal server in seguito, non è mai stato trovato in @Value. Se vuoi controllare @value, consulta il commento all'interno dello snippet. Il codice gestisce selezioni single e multiple.

$(document).on("keydown", ".chosen-container.chosen-newValuesAllowed input", function(e) { 
if (e.ctrlKey === true && e.keyCode === 73) { // CTRL + I
    e.preventDefault();
    var newValue = $(this).val();
    if (newValue) {            
        try {
            // only add if there is no option having the content/text of "input" yet!
            // instead of filter() for the content of <option> you can check on its @value by: find("option[val='...']") 
            var $selectElement = $(e.target).closest("div.chosen-container").prev(); // the previous sibling should be the <select>. If not, grab it some other way, e.g. via @id
            if (!$selectElement.find("option").filter(function () { return $(this).html() === newValue; }).length) {
                if (!$selectElement.attr("multiple")) { // unselect for single-select 
                    $selectElement.val('');
                }
                $selectElement.append('<option val="' + newValue + '" selected>' + newValue + '</option>');
                $selectElement.trigger('chosen:updated');    
            }
        } catch(error) {
            // pass
        }
        e.target.focus();
    }        
    return false; 
}
});

Un'altra soluzione sarebbe quella di chiamare la funzione innescabile Scelto: no_results Se devono essere aggiunti nuovi valori solo se non vi è esplicito alcun risultato:

$(".chosen-select.chosen-newValuesAllowed").on("chosen:no_results", function(e, data){
       var newValue = data.chosen.get_search_text();
       ...
 });
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top