普通网友 2018-05-29 08:33
浏览 85

如何在多个字段中添加select2

I have a form for add medical record, in input part for medicine, user can input more than 1 medicine, so I make a button to add multiple fields dynamically in that form, I use jquery.multifield.js for that.

In that fields, I have a <select> with select2 to choose the name of medicine. In the beginning before click the button (button to add fields) the <select> works fine, but if I click the button, they show the fields but I can't click the <select>. Here's my code. Hope somebody can help me.

the javascript is look like this.

<script src="<?=base_url('_assets/js/jquery.multifield.js')?>"></script>
<script src="<?=base_url('_assets/js/select2.min.js')?>"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $('.form-content').multifield({
            section: '.group',
            btnAdd:'#btnAdd',
            btnRemove:'.btnRemove',
        });
        $('.js-example-basic-single').select2({
          placeholder: 'Choose Medicine'
        });
    });
</script>

The jquery.multifield.js.

/**
 * jQuery Multifield plugin
 *
 * https://github.com/maxkostinevich/jquery-multifield
 */


// the semi-colon before function invocation is a safety net against concatenated
// scripts and/or other plugins which may not be closed properly.
;(function ( $, window, document, undefined ) {

    /*
     * Plugin Options
     * section (string) -  selector of the section which is located inside of the parent wrapper
     * max (int) - Maximum sections
     * btnAdd (string) - selector of the "Add section" button - can be located everywhere on the page
     * btnRemove (string) - selector of the "Remove section" button - should be located INSIDE of the "section"
     * locale (string) - language to use, default is english
     */

    // our plugin constructor
    var multiField = function( elem, options ){
        this.elem = elem;
        this.$elem = $(elem);
        this.options = options;
        // Localization
        this.localize_i18n={
        "multiField": {
          "messages": {
            "removeConfirmation": "Are You Sure Want To Delete Medicine?"
          }
        }
      };

        // This next line takes advantage of HTML5 data attributes
        // to support customization of the plugin on a per-element
        // basis. For example,
        // <div class=item' data-mfield-options='{"section":".group"}'></div>
        this.metadata = this.$elem.data( 'mfield-options' );
    };

    // the plugin prototype
    multiField.prototype = {

        defaults: {
            max: 0,
            locale: 'default'
        },


        init: function() {
            var $this = this; //Plugin object
            // Introduce defaults that can be extended either
            // globally or using an object literal.
            this.config = $.extend({}, this.defaults, this.options,
                this.metadata);

            // Load localization object
      if(this.config.locale !== 'default'){
            $this.localize_i18n = this.config.locale;
      }

            // Hide 'Remove' buttons if only one section exists
            if(this.getSectionsCount()<2) {
                $(this.config.btnRemove, this.$elem).hide();
            }

            // Add section
            this.$elem.on('click',this.config.btnAdd,function(e){
                e.preventDefault();
                $this.cloneSection();
            });

            // Remove section
            this.$elem.on('click',this.config.btnRemove,function(e){
                e.preventDefault();
                var currentSection=$(e.target.closest($this.config.section));
                $this.removeSection(currentSection);
            });

            return this;
        },


        /*
         * Add new section
         */
        cloneSection : function() {
            // Allow to add only allowed max count of sections
            if((this.config.max!==0)&&(this.getSectionsCount()+1)>this.config.max){
                return false;
            }

            // Clone last section
            var newChild = $(this.config.section, this.$elem).last().clone().attr('id', '').fadeIn('fast');


            // Clear input values
            $('input[type!="radio"],textarea', newChild).each(function () {
                $(this).val('');
            });

            // Fix radio buttons: update name [i] to [i+1]
            newChild.find('input[type="radio"]').each(function(){var name=$(this).attr('name');$(this).attr('name',name.replace(/([0-9]+)/g,1*(name.match(/([0-9]+)/g))+1));});
            // Reset radio button selection
            $('input[type=radio]',newChild).attr('checked', false);

            // Clear images src with reset-image-src class
            $('img.reset-image-src', newChild).each(function () {
                $(this).attr('src', '');
            });

            // Append new section
            this.$elem.append(newChild);


            // Show 'remove' button
            $(this.config.btnRemove, this.$elem).show();
        },

        /*
         * Remove existing section
         */
        removeSection : function(section){
            if (confirm(this.localize_i18n.multiField.messages.removeConfirmation)){
                var sectionsCount = this.getSectionsCount();

                if(sectionsCount<=2){
                    $(this.config.btnRemove,this.$elem).hide();
                }
                section.slideUp('fast', function () {$(this).detach();});
            }
        },

        /*
         * Get sections count
         */
        getSectionsCount: function(){
            return this.$elem.children(this.config.section).length;
        }

    };

    multiField.defaults = multiField.prototype.defaults;

    $.fn.multifield = function(options) {
        return this.each(function() {
            new multiField(this, options).init();
        });
    };



})( jQuery, window, document );

the form I create.

<form action="proses.php" method="post" autocomplete="off">
 <div class="form-content">
   <div class="row">
     <div class="col-md-12">
       <label>Medicine : </label>
        <p><button type="button" id="btnAdd" class="btn btn-primary btn-sm">Add Medicine</button></p>
     </div>
   </div>
   <div class="row group">
    <div class="col-md-4 pr-1" style="padding-left: 3%">
     <div class="form-group">                                                            
       <label>Medicine</label>
        <select name="medicine[]" class="form-control js-example-basic-single">
          <?php
            $query = "SELECT * FROM medicine WHERE stock_medicine > 0";
            $medicine = mysqli_query($con, $query) or die (mysqli_error($con));                                                         
             if(mysqli_num_rows($medicine ) > 0 ){                                                            
              while($data = mysqli_fetch_array($medicine )) { ?>
               <option value="<?=$data['id_medicine ']?>"><?=$data['name_medicine']?> - <?=$data['kind_medicine']?></option>
          <?php } 
             }?>
         </select>
      </div>
     </div>
     <div class="col-md-3 pr-1">
      <div class="form-group">
       <label for="">Total</label>
       <input name="total[]" type="number" class="form-control" placeholder="Total Medicine " value="" >
      </div>
     </div>
     <div class="col-md-3 pr-1">
      <div class="form-group">
       <label for="">Dose</label>
       <input type="text" name="dose[]" class="form-control" placeholder="Dose" >
      </div>
     </div>
     <div class="col-md-2">
      <div class="form-group">
       <button type="button" class="btn btn-danger btn-sm btnRemove">Delete</button>
      </div>
     </div>
   </div>
 </div>
</form>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 matlab数字图像处理频率域滤波
    • ¥15 ELGamal和paillier计算效率谁快?
    • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
    • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
    • ¥15 Arcgis相交分析无法绘制一个或多个图形
    • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
    • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
    • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
    • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
    • ¥30 3天&7天&&15天&销量如何统计同一行