1

Trying to create a form for a travel website. For one of the features I want to have the user select how many children they want to take on their trip. Subsequently, I then want the form to add new select fields the number of which depends on the amount of children selected. This is what I have so far:

HTML:

<select id="children">
    <option value ="0">0</option>
    <option value ="1">1</option>
    <option value ="2">2</option>
    <option value ="3">3</option>
    <option value ="4">4</option>
    <option value ="5">5</option>
    <option value ="6">6</option>
    <option value ="7">7</option>
</select>
<div id="childrenAge"></div>

JS

$("select#children").on("change", function() { 
    var number = parseInt($("#children").val());
    var newDropLabel = $("#childrenAge").append("<label>Age of children: </label>");
    var newDropList = $('<select class="Age"><option value="0">0</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><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><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option></select>');
    $("div#childrenAge").append(newDropLabel);
    for (i = 0; i < number; i++) {
       $("div#childrenAge").append(newDropList);   
    };
});

After selecting a number, this produces the new label and only one new select element. I've checked and the number variable gives the correct number value output. Not quite sure why it's not working.

I also want to add a label to each new select field, something like "Child 1" which increments each time depending on the amount of children chosen.

Any tips would be amazing.

Thanks.

1
  • So, if 2 is selected, you want to add two age-selection <select> elements, one for each child? Commented Dec 14, 2014 at 0:43

2 Answers 2

2

http://jsfiddle.net/ka4fm9ap/

In this way, whenever you change the number of children will be the exact number of select elements

$("select#children").on("change", function () {
    var number = parseInt($("#children").val());

    var label = "<label>Age of children: </label>";
    var newDropList = '<select class="Age"><option value="0">0</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><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><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option></select>';
    var html = '';
    $("#childrenAge").html('');
    html += label;
    for (i = 0; i < number; i++) {
        html += newDropList
    };

    $("#childrenAge").html(html);
});
Sign up to request clarification or add additional context in comments.

2 Comments

This is nice and simple, thanks a lot! Would you have any suggestions of how to add incrementing labels to the new select elements (e.g. Child 1, Child 2 etc)?
i hava a similar demand i have a multiple select i want foreach option seleted a new input is created is that possible ?
1

Here's one approach:

// binding a change event-handler to the '#children' element:
$('#children').on('change', function() {
  // when using parseInt() don't forget the radix (the number base),
  // in this case '10':
  var n = parseInt(this.value, 10),
  // creating a <label> element, setting its text to 'Age of child':
    label = $('<label />', {
      'text': 'Age of child'
    }),
  // creating a <select> element:
    select = $('<select />', {
      'class' : 'Age'
    }),
  // getting a reference to the element to which the new <select> elements are
  // going to be added, and emptying that element:
    recipient = $('#childrenAge').empty(),
  // empty variables for use within the later loop:
    cloneLabel, cloneSelect;
  // adding <option> elements to the select (for ages 0-17, assuming
  // that 18 is the appropriate age for 'adulthood' to begin):
  for (var o = 0; o < 18; o++) {
    // new Option(0,0) returns an <option> element, setting its value and text to
    // the variable 'o':
    select.append(new Option(o, o));
  }
  // if there's only one child it seems redundant to specify
  // 'child 1', so we just add the relevant <label> and <select>:
  if (n === 1) {
    recipient.append(label.append(select));
  // otherwise (assuming that we have a positive number of children:
  } else if (n > 0) {

    // using a for loop from 0 to the maximum number of children:
    for (var i = 0; i < n; i++) {
      // cloning the previously created <label> and <select> elements:
      cloneLabel = label.clone();
      cloneSelect = select.clone();

      // appending the cloned <label> to the recipient element:
      recipient.append(cloneLabel.text(function(_, t) {
        // updating the text of the <label>, appending a space and the current
        // value of 'i + 1':
        return t + ' ' + (i + 1);
      // and appending the <select> element to the <label>:
      }).append(cloneSelect));
    }
  }
});
label {
  display: block;
}
label select {
  margin-left: 0.5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="children">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
</select>
<div id="childrenAge"></div>

References:

2 Comments

This is an amazing answer! Thank you for taking the time to write it. However, the other answer above is a lot clearer for me to read at my level so I'll use that, but I will go through your answer and get my head around it. I wish I could up vote it, but my reputation is still low :(
No worries; obviously I'm biased so while I think I offer a better implementation there's not, really, a lot of difference. Except that in my version the <label> elements are used correctly (they should be associated with a specific form-element, not simply used to wrap arbitrary text, to demonstrate click on the <label>s in my demo and in the accepted-answer's demo). And I've deliberately accounted for the unnecessary automatic numbering of 'child 1' in the event of there being only one child.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.