在select上使用jQuery克隆HTML DIV

时间:2015-03-04 11:48:54

标签: javascript jquery html

我正在尝试根据为孩子数量选择的值克隆儿童年龄字段,以便选择每个孩子的年龄/。 HTML是:

第1次

  <div class="col-xs-4">
       <label>Copii</label>
       <div  class="selector">
          <select id='kids-1'  name="rooms[0][child]" class="full-width">
             <option value="0">0</option>
             <option value="1">1</option>
             <option value="2">2</option>
             <option value="3">3</option>
             >
          </select>
       </div>
    </div>
    <div class="age-of-children no-display">
       <div class="row">
          <div class="col-xs-4 child-age-field">
             <label>Copil 1</label>
             <div class="selector validation-field">
                <select id='age-1' class="full-width" name="rooms[0][age][]">
                   <option value="5">5</option>
                   <option value="6">6</option>
                   <option value="7">7</option>
                   <option value="8">8</option>
                   <option value="9">9</option>
                   <option value="10">10</option>
                   <option value="11">11</option>
                </select>
             </div>
          </div>
       </div>
    </div>

第2行

  <div class="col-xs-4">
       <label>Copii</label>
       <div  class="selector">
          <select id='kids-2'  name="rooms[1][child]" class="full-width">
             <option value="0">0</option>
             <option value="1">1</option>
             <option value="2">2</option>
             <option value="3">3</option>
             >
          </select>
       </div>
    </div>
    <div class="age-of-children no-display">
       <div class="row">
          <div class="col-xs-4 child-age-field">
             <label>Copil 1</label>
             <div class="selector validation-field">
                <select id='age-2' class="full-width" name="rooms[1][age][]">
                   <option value="5">5</option>
                   <option value="6">6</option>
                   <option value="7">7</option>
                   <option value="8">8</option>
                   <option value="9">9</option>
                   <option value="10">10</option>
                   <option value="11">11</option>
                </select>
             </div>
          </div>
       </div>
    </div>

使用的jQuery代码是

    // handle kid age from room 1
tjq('select[id=kids-1]').change(function(){
    var prev_kids = tjq('.age-of-children .child-age-field').length;
    tjq('.age-of-children').removeClass('no-display');
    var i;
    if (prev_kids > tjq(this).val()) {

        var current_kids = tjq(this).val();

        if (current_kids == 0) {
            current_kids = 1;
            tjq('.age-of-children').addClass('no-display');
        }

        for (i = prev_kids; i > current_kids; --i) {
            tjq('.age-of-children .child-age-field').eq(i-1).remove();
        }
    } else {
        for (i = prev_kids + 1; i <= tjq(this).val(); i++) {
            var clone_age_last = tjq('.age-of-children .child-age-field:last').clone();
            var clone_age = clone_age_last.clone();
            tjq('.age-of-children .row').append(clone_age);
            var name = clone_age.find('label').text().replace(/(\d+)/, function(match, p1)
            {
                return (parseInt(p1) + 1);
            });
            clone_age.find('label').text(name);
            clone_age.find('select').val(0);
            clone_age.find('.custom-select').text(0);
        }
    }
});
    // handle kid age from room 2
tjq('select[id=kids-2]').change(function(){
    var prev_kids = tjq('.age-of-children .child-age-field').length;
    tjq('.age-of-children').removeClass('no-display');
    var i;
    if (prev_kids > tjq(this).val()) {

        var current_kids = tjq(this).val();

        if (current_kids == 0) {
            current_kids = 1;
            tjq('.age-of-children').addClass('no-display');
        }

        for (i = prev_kids; i > current_kids; --i) {
            tjq('.age-of-children .child-age-field').eq(i-1).remove();
        }
    } else {
        for (i = prev_kids + 1; i <= tjq(this).val(); i++) {
            var clone_age_last = tjq('.age-of-children .child-age-field:last').clone();
            var clone_age = clone_age_last.clone();
            tjq('.age-of-children .row').append(clone_age);
            var name = clone_age.find('label').text().replace(/(\d+)/, function(match, p1)
            {
                return (parseInt(p1) + 1);
            });
            clone_age.find('label').text(name);
            clone_age.find('select').val(0);
            clone_age.find('.custom-select').text(0);
        }
    }
});

代码应根据所选儿童数选择器的值克隆年龄1字段,以便我可以为每个孩子选择年龄。

我创建了JSFiddle

1 个答案:

答案 0 :(得分:2)

我想你会重建一些HTML代码。

例如,我添加了.room-container元素,以便更容易地识别此元素和将包含的元素。

我希望我的代码解决您的问题。

JSFiddle

<强> HTML:

<div class="room-container">
<span> ROOM 1 </span>
      <div class="col-xs-4">
           <label>Copii</label>
           <div class="selector">
              <select id='kids-1'  name="rooms[0][child]" class="full-width">
                 <option value="0">0</option>
                 <option value="1">1</option>
                 <option value="2">2</option>
                 <option value="3">3</option>
              </select>
           </div>
        </div>
        <div class="age-of-children no-display">
           <div class="row">
              <div class="col-xs-4 child-age-field">
                 <label>Copil 1</label>
                 <div class="selector validation-field">
                    <select id='age-1' class="full-width" name="rooms[0][age][]">
                       <option value="5">5</option>
                       <option value="6">6</option>
                       <option value="7">7</option>
                       <option value="8">8</option>
                       <option value="9">9</option>
                       <option value="10">10</option>
                       <option value="11">11</option>
                    </select>
                 </div>
              </div>
           </div>
        </div>
</div>
<hr>
<div class="room-container">
<span>ROOM 2</span>

      <div class="col-xs-4">
           <label>Copii</label>
           <div  class="selector">
              <select id='kids-2'  name="rooms[1][child]" class="full-width">
                 <option value="0">0</option>
                 <option value="1">1</option>
                 <option value="2">2</option>
                 <option value="3">3</option>
                 >
              </select>
           </div>
        </div>
        <div class="age-of-children no-display">
           <div class="row">
              <div class="col-xs-4 child-age-field">
                 <label>Copil 1</label>
                 <div class="selector validation-field">
                    <select id='age-2' class="full-width" name="rooms[1][age][]">
                       <option value="5">5</option>
                       <option value="6">6</option>
                       <option value="7">7</option>
                       <option value="8">8</option>
                       <option value="9">9</option>
                       <option value="10">10</option>
                       <option value="11">11</option>
                    </select>
                 </div>
              </div>
           </div>
        </div>
</div>

<强> JS:

$(document).on('change', '[id^="kids-"]', function (){

    //Getting index of current room
    var roomIndex = $(this).attr('name').split('rooms[')[1].split('][child]')[0]; 

    //Getting room container
    var roomContainer = $(this).closest('.room-container');

    //Variable with childs number
    var childsNumber = Number($(this).val());

    //First element `.age-of-children` which is used as template for next childs
    var firstAgeOfChildsElement = $(roomContainer).find('.age-of-children').eq(0);

    //Number of total exists `.age-of-children` elements
    var ageOfChildsElementsCount = $(roomContainer).find('.age-of-children').length;

    //Number of `.age-of-children` elements which are not hidden
    var ageOfChildsVisibleElementsCount = $(roomContainer).find('.age-of-children').not('.no-display').length;

    //Adding new `.age-of-children` element if number of elements is lower than selected value BEGIN
    if(ageOfChildsElementsCount < childsNumber){

        for(var i=0;i<childsNumber;i++){

            if($(roomContainer).find('.age-of-children').eq(i).length < 1){

                //Cloning first `.age-of-children` element
               var newAgeOfChildsElement = $(firstAgeOfChildsElement).clone();

               //Setting new id for cloned `.age-of-children` element, and setting default value (5)
               $(newAgeOfChildsElement).find('select').attr('id', 'kid-'+i).val('5');

               //Setting new label title for clonded `.age-of-children` element
               $(newAgeOfChildsElement).find('label').text('Copil '+(i+1));

               //Appending cloned `.age-of-children` element to `roomContainer`
               $(roomContainer).append(newAgeOfChildsElement);
            }
        }
    }


    //Hidding all exists `.age-of-children` elements
    $(roomContainer).find('.age-of-children').addClass('no-display');


    //Unhidding exists `.age-of-children` elements if number of visible elements is lower than selected value (`index` of current element in loop have same or lower index than selected number of childs) 
    $(roomContainer).find('.age-of-children').each(function (){

        //Checing if index of current `.age-of-children` inside `roomContainer` element is lower than `childsNumber`
        if($(roomContainer).find('.age-of-children').index($(this)) < childsNumber){

            $(this).removeClass('no-display');
        }
    });

});

$(document).ready(function (){

    //Setting default value and triggering change for each item
    $('[id^="kids-"]').val(2).trigger('change');
});