Как добавить select2 в несколько полей

У меня есть форма для добавления медицинской карты, в части ввода для лекарств пользователь может ввести более 1 лекарства, поэтому я делаю кнопку для динамического добавления нескольких полей в эту форму, для этого я использую jquery.multifield.js.

В этих полях у меня есть <select> с select2, чтобы выбрать название лекарства. Вначале перед нажатием кнопки (кнопка для добавления полей) <select> работает нормально, но если я нажимаю кнопку, отображаются поля, но я не могу щелкнуть <select>. Вот мой код. Надеюсь, кто-нибудь сможет мне помочь.

JavaScript выглядит так.

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

Файл 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 );

форма, которую я создаю.

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

Вы должны применить select2 после добавления новой строки, тогда она будет работать.

Dani 29.05.2018 10:42

Я пробовал это разными способами, но все равно не работает. :(. Не могли бы вы дать мне подсказку или пример кода для применения select2 после добавления новой строки? @Dani

karimah 29.05.2018 15:37
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
2
226
0

Другие вопросы по теме