subhra subhra - 1 month ago 6
Javascript Question

Can not keep id serially of textbox using Javascript/Jquery

I have an issue.I am adding multiple textbox using

+
button and deleting using
-
button. Here i am unable to keep each textbox's id serially. I am explaining my code below.

<div class="form-group" id="intro-box">
<input type="text" style="width:85%;float:left;margin-bottom:5px;" class="form-control" id="introlabelname0" name="introlabelname" placeholder="Label Name" value="">
<input type="button" class="btn btn-success btn-sm" name="plus" id="plus" value="+" style="font-size:21px; line-height:12px; border-radius:4px; margin:3px; margin-bottom:6px;" onclick="addMore(1);">
</div>
<script>
var a = 0;
function addMore(i) {

a = a + 1;

i = a;

$("#plus").remove();

$('#intro-box').append('<div><input type="text" style="width:85%;float:left; margin-bottom:5px;" class="form-control" id="introlabelname' + i + '" name="introlabelname" placeholder="Label Name" value="">' +
'<input type="button" onclick="removeThis(' + i + ');" class="btn btn-danger btn-sm" name="minus" id="minus' + i + '" value="-" style="font-size:21px; line-height:12px; border-radius:4px; margin:3px; margin-bottom:6px;"></div>' +
'<div> <input type="button" class="btn btn-success btn-sm" name="plus" id="plus" value="+" style="font-size:21px; line-height:12px; border-radius:4px; margin:3px; margin-bottom:6px;" onclick="addMore(' + (i++) + ');"></div>');
}

function removeThis(j) {
$("#introlabelname" + j).remove();
$("#minus" + j).remove();
}
</script>


Here my problem is the id is increasing like
introlabelname0,introlabelname1,introlabelname2..
this but while suppose deleting
introlabelname1
textbox and adding again its coming
introlabelname0,introlabelname2,introlabelname3
like this. Here i need suppose
introlabelname1
deleting from
introlabelname0,introlabelname1,introlabelname2..
it should
introlabelname0,introlabelname1
and if adding again it should
introlabelname0,introlabelname1,introlabelname2
. Always all textbox id will remain serially from
0,1,2...
and so on. Here is my full code. Please help me.

Answer

The easy way is to loop over all the input box, and create the new ID(s) with index value. First of all give the text box class name :

class="form-control inputBox"

Then add this function :

function repopulate() {
  $( '.inputBox' ).each( function ( i, e) {
      $( this ).attr( 'id','introlabelname' + i );
      $( this ).next().attr( 'onClick', function (old,n) {
        return 'removeThis(' + i + ')';
      });
      $( this ).next().attr( 'id', function (old,n) {
        return 'minus' + i;
      });
  })  
}

Last, for each function calling, call this function :

repopulate();

Here is updated DEMO

p/s : you should edit the HTML,it not properly structured

Comments