Is there a way to dynamically ajax add elements through jquery chosen plugin?

后端 未结 8 1596
南旧
南旧 2020-12-15 06:50

I am trying to use \"Chosen\" plugin by harvest (http://harvesthq.github.com/chosen/) and it works for the static set of options I am passing. However, what I want is that w

相关标签:
8条回答
  • 2020-12-15 07:18

    in your ajax response, try

    var newOption = new Option("Text", __value__);  
    $("#tagSelection").append(newOption);  
    **/*  add this line */  
    $("#tagSelection").val(__value__);**  
    $("#tagSelection").trigger("liszt:updated");  
    
    0 讨论(0)
  • 2020-12-15 07:19

    Since version 1.0 some of the suggestions above are not relevant any longer. Here is all that is needed:

    --- /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:
    

    The options are as follows:

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

    This means that if "Orange" is not in the list of fruits, it would simply prompt:

    Press Enter to add: "Orange"

    The callback should register the new term by whatever means necessary and return the ID (or value in the context of the underlying select element) for the new option.

    var addTagCallback = function(tagText) {
      // do some synchronous AJAX 
      return tagID;
    };
    
    0 讨论(0)
提交回复
热议问题