Find and replace in a block of code with jQuery?

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.

Answers 1

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


Related Articles