如何正确调用jquery select2 api函数?

时间:2017-06-11 13:28:06

标签: jquery jquery-select2

我有这段代码:

<div class="row add_row">
    <div class="col-md-12">
        <div class="col-md-6">
            <div class="form-group">
                <label class="control-label col-sm-4">Add Department*</label>

                <div class="col-sm-8 department_input_fields_wrap">
                    <div style="margin-bottom: 5px;">
                        <select class="form-control department_id" name="department_id" required>
                            <option value="">--Select department--</option>
                            <?php
                                foreach($departments as $dep) {
                                    echo '<option value="'.$dep->id.'">'.$dep->department.'</option>';
                                }
                            ?>
                        </select>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-sm-6 add_job_title">
            <div class="form-group">
                <label class="control-label col-sm-4">Add Job Title</label>

                <div class="col-sm-8">
                    <div style="margin-bottom: 5px;">
                        <select class="form-control job_title" multiple="multiple" data-placeholder="Add job titles" name="job_title">

                        </select>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

这是我的jQuery代码

$(document).ready(function() {
    $(".department_id").change(function() {
        //$(".add_job_title").show();

        var id = $(this).val();
        var selector = $(this).parents('.col-md-6').siblings('.col-sm-6').find('.job_title');

        $.ajax({
            url: "<?php echo base_url('project/load_job_title_where'); ?>/" + id,
            type: "GET",
            dataType: "JSON",
            success: function(data) {
                $('.job_title').html("");
                // Use jQuery's each() to iterate over the opts value
                $.each(data, function(index, value) {                       
                    selector.prepend('<option value="' + value.dep_id + '">' + value.job_title + '</option>');
                });
            },
            error: function(jqXHR, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
    });
});

$(".job_title").select2();

$(document).ready(function() {
    var max_fields = 30; //maximum input boxes allowed
    var wrapper = $(".add_row"); //Fields wrapper
    var add_button = $(".add_department_field"); //Add button ID

    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div class="col-md-12"> <div class="col-md-6"> <div class="form-group"> <label class="control-label col-sm-4">Add Department*</label> <div class="col-sm-8 department_input_fields_wrap"> <div style="margin-bottom: 5px;"> <select class="form-control department_id" name="department_id" required> <option value="">--Select department--</option> <?php
                                            foreach($departments as $dep) {
                                                echo '<option value="'.$dep->id.'">'.$dep->department.'</option>';
                                            }
                                        ?> </select> </div> </div> </div> </div> <div class="col-sm-6 add_job_title"> <div class="form-group"> <label class="control-label col-sm-4">Add Job Title</label> <div class="col-sm-8"> <div style="margin-bottom: 5px;"> <select class="form-control job_title" multiple="multiple" data-placeholder="Add job titles" name="job_title"> </select> </div> </div> </div> </div> </div>'); //add input box
        }
    });

    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault();
        $(this).parent('div').remove();
        x--;
    })
});/* Script to add new textboxes for department end*/

这段代码的作用是,有一个select元素(department),通过它我可以选择一个部门,当我选择任何一个部门时,查询通过ajax运行一个控制器功能,并将所选结果预先添加到另一个选择元素(job title)。而且,当我点击“添加更多字段”按钮时,它会附加另一个选择行(department and job title),我可以在其中进行另一个选择。对于第一个选择,一切正常,但是当我单击按钮显示另一行时,似乎没有为该元素初始化select2()方法,并且job title选择元素也未填充数据。我不是很擅长jquery所以可能会有一些愚蠢的错误。那会是什么?

2 个答案:

答案 0 :(得分:0)

您必须重新初始化Select2函数以识别插入Current Loaded DOM的新元素job_title

试试这个:

$(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div class="col-md-12"> <div class="col-md-6"> <div class="form-group"> <label class="control-label col-sm-4">Add Department*</label> <div class="col-sm-8 department_input_fields_wrap"> <div style="margin-bottom: 5px;"> <select class="form-control department_id" name="department_id" required> <option value="">--Select department--</option> <?php
                                            foreach($departments as $dep) {
                                                echo '<option value="'.$dep->id.'">'.$dep->department.'</option>';
                                            }
                                        ?> </select> </div> </div> </div> </div> <div class="col-sm-6 add_job_title"> <div class="form-group"> <label class="control-label col-sm-4">Add Job Title</label> <div class="col-sm-8"> <div style="margin-bottom: 5px;"> <select class="form-control job_title" multiple="multiple" data-placeholder="Add job titles" name="job_title"> </select> </div> </div> </div> </div> </div>'); //add input box
        }
       // Re-Init Select2
       $(".job_title").select2();

    });

答案 1 :(得分:0)

您有两个问题:

  1. 在Dom Ready中调用select2。因此改变这些行:

    $( “JOB_TITLE”)SELECT2();

    $(document).ready(function(){

  2. 要:

    $(document).ready(function() {
    
            //
            // first ISSUE: call select2 inside dom ready...
            //
            $(".job_title").select2();
    
    1. 在ajax调用的成功部分中,您需要调用select2来初始化新添加的select元素,或者在添加元素后需要触发change事件。
    2. 在下面的代码片段中,我使用了错误aiax调用,以便使代码段自动运行

      $(document).ready(function() {
          $(".department_id").change(function() {
              //$(".add_job_title").show();
      
              var id = $(this).val();
              var selector = $(this).parents('.col-md-6').siblings('.col-sm-6').find('.job_title');
      
      
              $.ajax({
                  url: "<?php echo base_url('project/load_job_title_where'); ?>/" + id,
                  type: "GET",
                  dataType: "JSON",
                  success: function(data) {
                      $('.job_title').html("");
                      // Use jQuery's each() to iterate over the opts value
                      $.each(data, function(index, value) {
                          selector.prepend('<option value="' + value.dep_id + '">' + value.job_title + '</option>');
                      });
                  },
                  error: function(jqXHR, textStatus, errorThrown) {
                      //
                      // for demo purposes
                      //
                      $('.job_title').empty();
                      // Use jQuery's each() to iterate over the opts value
                      $.each([{dep_id: 0, job_title: 1010}, {dep_id: 222, job_title: 222}], function(index, value) {
                          selector.prepend('<option value="' + value.dep_id + '">' + value.job_title + '</option>').trigger('change');
                      });
                  }
              });
          });
      });
      
      
      $(document).ready(function() {
      
          //
          // first ISSUE: call select2 inside dom ready...
          //
          $(".job_title").select2();
      
      
          var max_fields = 1; //maximum input boxes allowed
          var wrapper = $(".add_row"); //Fields wrapper
          var add_button = $(".add_department_field"); //Add button ID
      
          var x = 1; //initlal text box count
          $(add_button).click(function(e){ //on add input button click
              e.preventDefault();
              if(x < max_fields){ //max input box allowed
                  x++; //text box increment
                  $(wrapper).append('<div class="col-md-12"> <div class="col-md-6"> <div class="form-group">  ' +
                          '<label class="control-label col-sm-4">Add Department*</label>  ' +
                          '<div class="col-sm-8 department_input_fields_wrap"> <div style="margin-bottom: 5px;">  ' +
                          '<select class="form-control department_id" name="department_id" required> <option value="">--Select department--</option>' +
                      '<option value="1">1</option>' +
                  '</select> </div> </div> </div> </div> <div class="col-sm-6 add_job_title">  ' +
                  '<div class="form-group"> <label class="control-label col-sm-4">Add Job Title</label>  ' +
                  '<div class="col-sm-8"> <div style="margin-bottom: 5px;">  ' +
                  '<select class="form-control job_title" multiple="multiple" data-placeholder="Add job titles" name="job_title"> </select> </div> </div> </div> </div> </div>'); //add input box
                  $(wrapper).find('select').select2();
              }
          });
      
          $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
              e.preventDefault();
              $(this).parent('div').remove();
              x--;
          })
      });/* Script to add new textboxes for department end*/
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
      
      <link rel="stylesheet" href="https://rawgit.com/select2/select2/master/dist/css/select2.min.css">
      <script src="https://rawgit.com/select2/select2/master/dist/js/select2.min.js"></script>
      
      
      
      <button type="button" class="btn add_department_field">Add Button</button>
      <div class="row add_row">
          <div class="col-md-12">
              <div class="col-md-6">
                  <div class="form-group">
                      <label class="control-label col-sm-4">Add Department*</label>
      
                      <div class="col-sm-8 department_input_fields_wrap">
                          <div style="margin-bottom: 5px;">
                              <select class="form-control department_id" name="department_id" required>
                                  <option value="">--Select department--</option>
                                      <option value="1">1</option>
                              </select>
                          </div>
                      </div>
                  </div>
              </div>
      
              <div class="col-sm-6 add_job_title">
                  <div class="form-group">
                      <label class="control-label col-sm-4">Add Job Title</label>
      
                      <div class="col-sm-8">
                          <div style="margin-bottom: 5px;">
                              <select class="form-control job_title" multiple="multiple" data-placeholder="Add job titles" name="job_title">
                                  <option value="11">11</option>
                                  <option value="22">22</option>
                              </select>
                          </div>
                      </div>
                  </div>
              </div>
          </div>
      </div>