Search code examples
javascriptjquerycountershow-hide

Removal of added div should result in decrease of counter and next subsequent divs should be renamed as per the order


On click of add button, I can able to add 7 divs in an order. And when I try to remove a div in between, then, sebsequent divs should be renamed/updated as per the order.

My HTML

<div class="container">
  <div class="row">
    <div id="driver<%=i%>" class="panel panel-default knowledge">
      <div class="panel-heading2">
        <h4 class="panel-title collapsed" data-toggle="collapse" data-parent="#accordion" data-target="#collapse<%=i%>" aria-expanded="false">
          <a class="accordion-toggle driver-title<%=i%>">Driver <%=i%></a>
          <div class="pull-right"><span class="glyphicon glyphicon-plus"></span></div>
        </h4>
      </div>
      <div id="collapse<%=i%>" class="panel-collapse collapse" aria-expanded="false" style="height: 0px;">
        <div class="panel-body">
          <div class="col-sm-12 col-md-12 col-lg-12">                     
            <div class="gap gap-mini"></div>
            <div class="form-group">
              <label class="col-sm-4 control-label">Full Name</label>
              <div class="col-sm-6">
                <input type="text" id="drname<%=i%>" name="drname"  class="form-control" placeholder="Full Name">
              </div>
            </div>
            <div class="remove_wrap_but">
              <a href="javascript:void(0)" class="btn btn-yellow" id="<%=i%>" onclick="removeValueItem(this.id)">- remove driver</a>
            </div>
          </div>
        </div>                   
      </div>
    </div>
  </div>
</div>

I'm looping this content 7 times so that I can add divs 7 times in a sequential order like 1 2 3 4 5 6 7.

My javascript code is as follows.

var valueItemCount = 2;
  if($('#hdItemCount').val()!='2'){
    valueItemCount =$('#hdItemCount').val();
  }
  var isRemove = false;
  var isAdded = false;
  $('#hdItemCount').val(valueItemCount);

  function addValueItem() {
      //alert(isRemove);
      //$('#errmessage').html("");
      console.log("valueItemCount addValueItem   : "+valueItemCount);
      console.log("isRemove    : "+isRemove);
      if(valueItemCount <8) {
        if (isRemove && !isAdded) ++valueItemCount;
        // alert(valueItemCount);
        $('#driver' + valueItemCount).show();
        ++valueItemCount;
        $('#hdItemCount').val(valueItemCount);
        isAdded = true;
      } else {
        //$('#errmessage').html("Maximm Limit Reached");
      }
      // alert(isAdded);
      console.log("isAdded    : "+isAdded);
  }

  function removeValueItem(cnt) {
    if($('#hdItemCount').val()!='2'){
      valueItemCount =$('#hdItemCount').val();
    }
    if (isAdded && !isRemove) {--valueItemCount;}
    alert(cnt);
    console.log(" removeValueItem cnt    : "+cnt);
    console.log("valueItemCount   removeValueItem : "+valueItemCount);
    var count=Number(cnt)+1
    //alert('count1111'+count);
    $('#driver' + cnt).hide();
    if (isAdded && isRemove) {  --valueItemCount; }
    $('#hdItemCount').val(valueItemCount);
    //alert(count);
    console.log("count   : "+count);
    var i;
    for (i = count; i <8; i++) {
      var j=i-1;
      $('#'+i).attr('id',j);
      $('#driver' + i).attr('id','driver'+j);
      $('.driver-title' + i).text('Driver '+j);
    }
    isRemove = true;
    console.log(" isRemove remove    : "+isRemove);
    console.log(" isAdded remove    : "+isAdded);
    if (valueItemCount == 2) {
      isRemove = false;
      isAdded = false;
    }
  }
  if($('#hdItemCount').val()!='2'){
      valueItemCount =$('#hdItemCount').val();
  }
  var itemcnt =  '<%=cntvalue%>';
  for(var i=valueItemCount;i<=8;i++){
      $('#driver'+i).hide();
  }
  for (var i=1;i<valueItemCount;i++){
      console.log("valueItemCount   : "+valueItemCount);
      $('#driver'+i).show();
     $('#hdItemCount').val(valueItemCount);
  }

With this code, I can able to add divs upto 7 which is correct. when I try to delete one particular div in between the order, subsequent divs got renamed but later, i'm unable to add / remove further. Remove is working only once.

Can anyone help on this.


Solution

    1. Can add up to 7 drivers in total by clicking add Icon
    2. Removing any driver removes particular driver, thereby reordering all Ids.
    3. Removing each driver, will give space to add another driver at last, such that their total count won't exceed 7;

    function addValueItem() {
      if ($('div.driverContainer div.knowledge[id*=driver]:not(.hidden)').length < 7) {
        var templateDiv = $('.driver-template').clone(true);
        templateDiv.removeClass('driver-template hidden').addClass('container driverContainer');
        templateDiv.clone(true).insertAfter($('div.driverContainer:last'));
        reAssignIDs();
      }
    }
    
    function removeValueItem(elem) {
      if ($('div.driverContainer div.knowledge[id*=driver]:not(.hidden)').length == 1) {
        addValueItem();
      }
      $(elem).closest('div.driverContainer').remove();
      reAssignIDs();
    }
    
    function reAssignIDs() {
      var Index = 1;
      $('div.driverContainer div.knowledge[id*=driver]').each(function() {
        if (!$(this).hasClass('hidden')) {
          $(this).attr('id', 'driver' + Index);
          $(this).find('h4').attr('data-target', '#collapse' + Index);
          $(this).find('h4 a').text('Driver ' + Index);
          $(this).find('div[id*=collapse]').attr('id', 'collapse' + Index);
          $(this).find('input[id*=drname]').attr('id', 'drname' + Index);
          $(this).find('.remove_wrap_but a.btn-yellow').attr('id', Index);
          Index++;
        }
      });
      $(".glyphicon.glyphicon-plus").addClass('hidden');
      if ($('div.driverContainer div.knowledge[id*=driver]:not(.hidden)').length < 7) {
        $(".glyphicon.glyphicon-plus:last").removeClass('hidden');
      }
    }
    $(".panel-title").click(function(e) {
      if (!$(e.target).is('.glyphicon.glyphicon-plus'))
        $(this).closest('.row').find('.panel-collapse').toggleClass('collapse');
    });
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div class="driver-template hidden">
      <div class="row">
        <div id="driver" class="panel panel-default knowledge">
          <div class="panel-heading2">
            <h4 class="panel-title collapsed" data-toggle="collapse" data-parent="#accordion" data-target="#collapse" aria-expanded="false">
              <a class="accordion-toggle driver-title1">Driver X</a>
              <div class="pull-right"><span class="glyphicon glyphicon-plus" onclick="addValueItem()"></span></div>
            </h4>
          </div>
          <div id="collapse1" class="panel-collapse collapse" aria-expanded="false" style="height: 0px;">
            <div class="panel-body">
              <div class="col-sm-12 col-md-12 col-lg-12">
                <div class="gap gap-mini"></div>
                <div class="form-group">
                  <label class="col-sm-4 control-label">Full Name</label>
                  <div class="col-sm-6">
                    <input type="text" id="drname" name="drname" class="form-control" placeholder="Full Name">
                  </div>
                </div>
                <div class="remove_wrap_but">
                  <a href="javascript:void(0)" class="btn btn-yellow" id="" onclick="removeValueItem(this)">- remove driver</a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="container driverContainer">
      <div class="row">
        <div id="driver1" class="panel panel-default knowledge">
          <div class="panel-heading2">
            <h4 class="panel-title collapsed" data-toggle="collapse" data-parent="#accordion" data-target="#collapse1" aria-expanded="false">
              <a class="accordion-toggle driver-title1">Driver 1</a>
              <div class="pull-right"><span class="glyphicon glyphicon-plus" onclick="addValueItem()"></span></div>
            </h4>
          </div>
          <div id="collapse1" class="panel-collapse collapse" aria-expanded="false" style="height: 0px;">
            <div class="panel-body">
              <div class="col-sm-12 col-md-12 col-lg-12">
                <div class="gap gap-mini"></div>
                <div class="form-group">
                  <label class="col-sm-4 control-label">Full Name</label>
                  <div class="col-sm-6">
                    <input type="text" id="drname1" name="drname" class="form-control" placeholder="Full Name">
                  </div>
                </div>
                <div class="remove_wrap_but">
                  <a href="javascript:void(0)" class="btn btn-yellow" id="1" onclick="removeValueItem(this)">- remove driver</a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    </div>

    *Please note that I've created a template div with class 'driver-template'. Whils clicking 'Add' option, I just inserted this template at end, and renamed all ids. You can even keep 7 drivers initially using your loop. Further working like removing and adding will work accordingly using this logic.*

    If still this is not what you are required, please explain more.