Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone HTML DIV with jQuery on select

I am trying to clone the Child Age Field based on the value selected for the Number of Kids in order to select the age pf each kid/. HTML is:

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

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

And the jQuery code that is use is

    // 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);
        }
    }
});

The code should clone the age 1 field based on the value selected of the kid count selector so i can chose the age for each kid.

I have created the JSFiddle

like image 835
GeorgeB Avatar asked Mar 04 '15 11:03

GeorgeB


1 Answers

I think You will rebuild some of Your HTML code.

For example, I was added .room-container elements for easier identification with this element and elements which will contains.

I hope my code resolve Your problem.

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');
});
like image 91
Mateusz Mania Avatar answered Nov 08 '22 06:11

Mateusz Mania