Domanda

Sto cercando di usare il "Prescelto" plugin dalla vendemmia (http://harvesthq.github.com/chosen/) e funziona per la statica set di opzioni che sto passando.Tuttavia, quello che voglio è che ogni volta che qualcuno tipologie di qualcosa che non è in pre-riempite le opzioni, quindi dovrebbe inviare al server come una nuova opzione e sulla risposta positiva, voglio non solo aggiungere che l'elenco di opzioni, ma anche selezionarlo.

Ricaricare le opzioni è abbastanza semplice:

// In ajax response
var newOption = new Option("Text", __value__);
$("#tagSelection").append(newOption);
$("#tagSelection").trigger("liszt:updated");

Tuttavia, non so come fare "Scelto" plugin prendere questo come valore.Mi piacerebbe fare qualcosa di simile

$("#tagSelection").trigger("liszt:select:__value__"); 

o qualcosa di simile.

Qualche suggerimento?

(ps:Sto cercando di costruire un "tagging" plugin basato su scelte.Così, se il tag digitato non esiste, verrà aggiunto al server e quindi selezionare subito.)

È stato utile?

Soluzione 2

Questi sono il set completo di modifiche che ho fatto al plugin scelto (versione jquery) per risolvere questo problema

Chosen.prototype.choice_build = function(item) {
  this.new_term_to_be_added = null; 
  // ....
};

Chosen.prototype.no_results = function(terms) {
  // ....
  no_results_html.find("span").first().html(terms);
  this.new_term_to_be_added = terms;
  return this.search_results.append(no_results_html);
};


Chosen.prototype.keydown_checker = function(evt) {
       // ...
        case 13:
          if(this.new_term_to_be_added != null &&  this.options.addNewElementCallback != null) {
              var newElement = this.options.addNewElementCallback(this.new_term_to_be_added);


              if(newElement!=null && newElement.length == 1) {
                  // KEY TO SOLVING THIS PROBLEM
                  this.result_highlight = newElement;
                  // This will automatically trigger the change/select events also. 
                  // Nothing more required.
                  this.result_select(evt);
              }
              this.new_term_to_be_added = null;
          }
          evt.preventDefault();
          break;
          // ...
};
.

The this.new_term_to_be_added mantiene la stringa attualmente digitata che non è tra le opzioni predefinite.

Le opzioni.AddnewelementCallback è il callback alla funzione di chiamata per consentire loro di elaborarlo (inviarlo al server ecc.) E deve essere sincrono.Di seguito lo scheletro:

var addTagCallback = function(tagText) {
    var newElement = null;
    $.ajax({url : that.actionUrl, 
        async : false, 
        dataType: "json",
        data : { // ....},
        success : function(response) {
        if(response) {
                            $('#tagSelection').append(
                                $('<option></option>')
                                      .val(data.Item.Id)
                                      .html(data.Item.Value)
                                      .attr("selected", "selected"));
            $("#tagSelection").trigger("liszt:updated");
            // Get the element - will necessarily be the last element - so the following selector will work
            newElement = $("#tagSelection_chzn li#tagSelection_chzn_o_" + ($("#tagSelection option").length - 1));
        } else {
            // Handle Error
        }
    }});
    return newElement;
};
.

The Newelement è un elemento jQuery: l'ultimo oggetto LI aggiunto all'elenco delle opzioni.

facendo questo.result_highlight= newelement;e questo.result_select (EVT);Dico al plugin scelto di selezionare questo.Questo funziona se è un singolo selezione o un multi-select.La soluzione di Rifky funzionerà solo per Single Select.

Altri suggerimenti

Ho appena fatto questo.Non mi piaceva la linea di Shreeni per impostare selezionati (senza offesa) quindi sono andato con

$('#tagSelection').append(
    $('<option></option>')
        .val(data.Item.Id)
        .html(data.Item.Value)
        .attr("selected", "selected"));
$("#tagSelection").trigger("liszt:updated");
.

che personalmente penso sia un po 'più pulito (testato con scatola multiselect e funziona bene)

Una forcella che contiene la funzione desiderata non è stata creata qui.Questa forcella è indicato come il koenpunt forcella.

Puoi seguire la discussione per questa funzione harvesthq github sito

La mia sintesi di quello che è successo:

  1. Molte persone non vogliono questa funzione
  2. Alcune persone hanno creato un pull-richieste con una proposta di soluzione
  3. La soluzione migliore è pull-richiesta 166
  4. L'autore di "scelta", ha deciso di non includere la funzione
  5. koenpunt (l'autore di pull-richiesta 166) creato un fork di 'scelta'
  6. Persone hanno iniziato ad abbandonare il harvesthq versione di "scelta", in favore della koenpunt forcella

Poiché la versione 1.0 alcuni dei suggerimenti sopra non sono più rilevanti.Ecco tutto ciò che è necessario:

--- /home/lauri/Downloads/chosen_v1.0.0 (original)/chosen.jquery.js
+++ /home/lauri/Downloads/chosen_v1.0.0 (modified)/chosen.jquery.js
@@ -408,8 +408,18 @@
           break;
         case 13:
           evt.preventDefault();
-          if (this.results_showing) {
+          if (this.results_showing && this.result_highlight) {
             return this.result_select(evt);
+          }
+          var new_term_to_be_added = this.search_field.val();
+          if(new_term_to_be_added && this.options.add_term_callback != null) {
+              var newTermID = this.options.add_term_callback(new_term_to_be_added);
+              if(newTermID) {
+                this.form_field_jq.append(
+                  $('<option></option>').val(newTermID).html(new_term_to_be_added).attr("selected", "selected")
+                );
+                this.form_field_jq.trigger("chosen:updated");
+              }
           }
           break;
         case 27:
.

Le opzioni sono le seguenti:

{add_term_callback: addTagCallback, no_results_text:'Press Enter to add:'}
.

Ciò significa che se "arancione" non è nell'elenco dei frutti, si chiamerebbe semplicemente:

.

Premere INVIO per aggiungere: "Orange"

Il callback dovrebbe registrare il nuovo termine con qualsiasi mezzo necessario e restituire l'ID (o il valore nel contesto dell'elemento di selezione sottostante) per la nuova opzione.

var addTagCallback = function(tagText) {
  // do some synchronous AJAX 
  return tagID;
};
.

Nella tua risposta Ajax, prova

var newOption = new Option("Text", __value__);  
$("#tagSelection").append(newOption);  
**/*  add this line */  
$("#tagSelection").val(__value__);**  
$("#tagSelection").trigger("liszt:updated");  
.

Penso che non sia la migliore pratica, ma questo codice funziona per me.DATA RESORT ha un tag<option> HTML

$.post("url.php",{data:data},function(data){
$('.choosen').empty().append(data);
$(".choosen").trigger("liszt:updated");
});
.

Lo faccio semplicemente in questo modo e funziona perfettamente:

// this variable can be filled by an AJAX call or so
var optionsArray = [ 
    {"id": 1, "name": "foo"}, 
    {"id": 2, "name": "bar"}
];

var myOptions = "<option value></option>";
for(var i=0; i<optionsArray.length; i++){
    myOptions +=  '<option value="'+optionsArray[i].id+'">'+optionsArray[i].name+'</option>';
}

// uses new "chosen" names instead of "liszt"
$(".chosen-select").html(myOptions).chosen().trigger("chosen:updated");
.

Non è necessario molto stress, mantienilo semplice.È necessario aggiungere la risposta Ajax in Seleziona casella HTML e quindi aggiornare scelti.

Sembrerà ..

Codice:

var baseURL='Your Url';

 $.ajax({

           type: "POST",

           url: baseURL+"Your function", //enter path for ajax

           data: "id="+id,   //pass any details

           success: function(response){   //get response in json_encode()formate
                  
                 var json_data = JSON.parse(response);

                  var i=0; var append='';

                  if((json_data['catss_data'].length > 0)){

                      for(i=0;i < json_data['response_data'].length; i++){

                          append+="<option value='"+json_data['response_data'][i].category_name+"'>"+json_data['response_data'][i].category_name+"</option>";
                                   // make response formate in option 

                        }

                    $('#(selectbox-id)').html(append);   // enter select box id and append data in it

                     }

                 }

           $("#(selectbox-id)").trigger("chosen:updated");  // enter select box id and update chosen

   });   
.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top