1

I have this HTML:

<div class="group-sizing">
    <div class="form-group">
        <div>
            <h3>Guest <span>1</span> Welcome</h3>
            <div>
                <select id="level1"></select>
            </div>
        </div>
    </div>
</div>

I have this function:

var guestBlock = $(".group-sizing").html();
$("#guestNum").change(function(){
    var count = $(this).val();
    $(".group-sizing .form-group:gt("+(count-1)+")").remove();
    for (var i = $(".group-sizing .form-group").length; i < count; i++){
        $(guestBlock).find(?????????).html(i); //find and change span and id of select
        $(".group-sizing").append(guestBlock); //then print the block
    };
});

In $(guestBlock).find() I want to find the span from the <h3> and the id from the <select>. Then increment them by i but so far I haven't been able to get it. It always prints with 1 in those spaces.

6
  • what is the expected output Commented Mar 22, 2016 at 3:49
  • Let me be an ass here, ????????? is not a valid selector -- so what selectors have you tried? Commented Mar 22, 2016 at 3:49
  • what calls this: $("#guestNum").change(function(){ Commented Mar 22, 2016 at 3:50
  • <select id="guestNum"> is a select earlier in the HTML. That calls the change function. Commented Mar 22, 2016 at 3:55
  • Output expected is the entire block but with <h3>Guest <span>2</span> Welcome</h3> and <select id="level2"> and so on according to the for statement. Commented Mar 22, 2016 at 3:56

1 Answer 1

2

You can use cloning to solve it like

var $guestBlock = $(".group-sizing > .form-group").first().clone();
$("#guestNum").change(function() {
  var count = $(this).val();
  var $groups = $(".group-sizing > .form-group");
  $groups.slice(count).remove();
  for (var i = $groups.length; i < count; i++) {
    var $clone = $guestBlock.clone().appendTo('.group-sizing');
    $clone.find('h3 span').text(i + 1);
    $clone.find('select').attr('id', 'level' + (i + 1));
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="group-sizing">
  <div class="form-group">
    <div>
      <h3>Guest <span>1</span> Welcome</h3>
      <div>
        <select id="level1"></select>
      </div>
    </div>
  </div>
</div>


<select id="guestNum">
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
</select>

Sign up to request clarification or add additional context in comments.

Comments

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.