JavaScript issue with comma separated values

Hi, I have the following Code:

$('#btAdd').click(function() {
	var groupname = $(this).attr('data-id');
	var isselect = $(this).attr('data-coral');
    if (cnt <= 9999) {
        cnt = cnt + 1;
		arry.push(cnt);
			$(container).append('<span class="twodelete"><div class="margin5px modal-partition"><label for="Name">Name</label><input data-placement=bottom type=text name="field' + '' + cnt + '"  id="field' + '' + cnt + '" class=form-control data-rule-required=true data-msg-required="Provide field details" /></div><div class="margin5px modal-partition"><label for="status' + '' + cnt + '">Status</label><select name="status' + '' + cnt + '" id="status' + '' + cnt + '" class="form-control" data-rule-required="true" data-msg-required="Provide Status details"><option value="1">Active</option><option value="0">Inactive</option></select></div><input type="button" id="btRemove" rel="' + groupname + '_' + cnt + '" value="X" class="sectionBtn bt" /></span>');
    }
	arrys = arry.join(",");
	$(newitems).append('<input type="hidden" name="insertRecords" id="insertRecords" value="'+arrys+'"/>');
	$('.buttonsPlaceHolder').before(container);
	$('.buttonsPlaceHolder').after(newitems);
});
$(document).on('click', '#btRemove', function(){
	$(this).closest('.twodelete').remove();
});

Open in new window


the problem is it is creating the insertrecords input field like this:

insertRecords:2
insertRecords:2,3
insertRecords:2,3,4
insertRecords:2,3,4,5
insertRecords:2,3,4,5,6
insertRecords:2,3,4,5,6,7
insertRecords:2,3,4,5,6,7,8
insertRecords:2,3,4,5,6,7,8,9

Open in new window


also it is keeping the old deleted codes like 3,4,5,6,7,8 - i deleted but it is still showing in this

How can i fix this, please guide
LVL 16
Gurpreet Singh RandhawaCEOAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
The problem is on line 6
arry.push(cnt);

Open in new window

each time you click on btnAdd it adds an item to the array but when you click on btnRemove you do not remove the item from the array.
Here is what you need to do.
1. Make your life easier and add a data attribute to your inserted item so you can get access to the cnt value more easily like this
 ... '<span class="twodelete" data-cnt="' +  cnt +'">

Open in new window


2. In your remove code you can now get the cnt value easily like this
$(document).on('click', '#btRemove', function(){
  var item = $(this).closest('.twodelete');
  var v = item.data('cnt');
  ...
});

Open in new window


3. All that is left is to add the code to remove the value from the array and you can do that like this

for(var i = arry.length - 1; i >= 0; i--) {
  if(arry[i] === v) {
    arry.splice(i, 1);
    break;
  }
}

Open in new window


Putting it all together
$('#btAdd').click(function() {
  var groupname = $(this).attr('data-id');
  var isselect = $(this).attr('data-coral');
    if (cnt <= 9999) {
        cnt = cnt + 1;
    arry.push(cnt);
      $(container).append('<span class="twodelete" data-cnt="' + cnt + '"><div class="margin5px modal-partition"><label for="Name">Name</label><input data-placement=bottom type=text name="field' + '' + cnt + '"  id="field' + '' + cnt + '" class=form-control data-rule-required=true data-msg-required="Provide field details" /></div><div class="margin5px modal-partition"><label for="status' + '' + cnt + '">Status</label><select name="status' + '' + cnt + '" id="status' + '' + cnt + '" class="form-control" data-rule-required="true" data-msg-required="Provide Status details"><option value="1">Active</option><option value="0">Inactive</option></select></div><input type="button" id="btRemove" rel="' + groupname + '_' + cnt + '" value="X" class="sectionBtn bt" /></span>');
    }
  arrys = arry.join(",");
  $(newitems).append('<input type="hidden" name="insertRecords" id="insertRecords" value="'+arrys+'"/>');
  $('.buttonsPlaceHolder').before(container);
  $('.buttonsPlaceHolder').after(newitems);
});
$(document).on('click', '#btRemove', function(){
  var item = $(this).closest('.twodelete');
  var v = item.data('cnt');
  for(var i = arry.length - 1; i >= 0; i--) {
    if(arry[i] === v) {
      arry.splice(i, 1);
      break;
    }
  }
  item.remove();
});

Open in new window

The code above is untested as I don't have access to the rest of the page but the logic should be sound.
Gurpreet Singh RandhawaCEOAuthor Commented:
Thanks, it does work but after adding 2 elements i removed again two elements

but why the insert is coming like this

I want that insertrecords input field should display only once

field1:Phase 2
status1:1
lstItem:0
lstgroupName:client_type
field2:Phase 3
status2:0
insertRecords:2
insertRecords:2,3
insertRecords:2,3,4

Open in new window

Julian HansenCommented:
The reason is that you are appending a new input everytime you you add an item you run this code
$(newitems).append('<input type="hidden" name="insertRecords" id="insertRecords" value="'+arrys+'"/>');

Open in new window

There are several things wrong with this

1. I don't think you want a new hidden input for each button you create - you seem to be populating it with the cnt values for the items that have been added so I would imagine you only want one of them
2. You are creating the inputs with the same name and id - id's must be unique and using the same name is going to create issues when trying to access the values

Why not make your insertRecords hidden input a static item on your page i.e. add it to the form and then remove the above line from the script and instead do the following

$('#insertRecords').val(arrys);

Open in new window

Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Julian HansenCommented:
Something like this
<form ...>
  <!-- add your insert records hidden input to your form rather than creating it in script -->
  <input type="hidden" name="insertRecords" id="insertRecords" />
...
</form>
<script>
...
$('#btAdd').click(function() {
  var groupname = $(this).attr('data-id');
  var isselect = $(this).attr('data-coral');
    if (cnt <= 9999) {
        cnt = cnt + 1;
    arry.push(cnt);
      $(container).append('<span class="twodelete" data-cnt="' + cnt + '"><div class="margin5px modal-partition"><label for="Name">Name</label><input data-placement=bottom type=text name="field' + '' + cnt + '"  id="field' + '' + cnt + '" class=form-control data-rule-required=true data-msg-required="Provide field details" /></div><div class="margin5px modal-partition"><label for="status' + '' + cnt + '">Status</label><select name="status' + '' + cnt + '" id="status' + '' + cnt + '" class="form-control" data-rule-required="true" data-msg-required="Provide Status details"><option value="1">Active</option><option value="0">Inactive</option></select></div><input type="button" id="btRemove" rel="' + groupname + '_' + cnt + '" value="X" class="sectionBtn bt" /></span>');
    }
  arrys = arry.join(",");
  $('#insertRecords').val(arrys);
  $('.buttonsPlaceHolder').before(container);
  $('.buttonsPlaceHolder').after(newitems);
});
$(document).on('click', '#btRemove', function(){
  var item = $(this).closest('.twodelete');
  var v = item.data('cnt');
  for(var i = arry.length - 1; i >= 0; i--) {
    if(arry[i] === v) {
      arry.splice(i, 1);
      break;
    }
  }
  item.remove();
});
...
</script>

Open in new window

Gurpreet Singh RandhawaCEOAuthor Commented:
but it does not delete from the insertrecords which is the removal function you have written,

suppose my list comes as 3,6,7

so you will ask why 3 and then 6, because i added 4,5, and then deleted again

now when i remove that , it does remove the item from insertarrays which it should do basically

correct me if i am wrong
Julian HansenCommented:
Can you post more of your code or provide a link. I can give you a working sample but would prefer not to have to type on all the other bits.
Gurpreet Singh RandhawaCEOAuthor Commented:
link seems not possible but code is gonna like this:

This is the first time i dynamically added the elements

<form method="post" name="listSections" id="listSections" class="formpadd" novalidate="novalidate">
	<fieldset><h4 class="sectionTitleh4" id="section-path"></h4>
		
			<div class="floatingLeft"><label class="margin10pxvisiblity">position</label></div>
			<div class="floatingRight"><input type="button" data-coral="0" data-id="position" id="btAdd" value="Add Element" tabindex="-1" class="bt"><input type="button" id="btRemoveAll" value="Remove All" class="bt"></div>
			
				<span class="fixed">
				<div class="margin5px modal-partition aftersect">
					<label for="name1">Name</label>
					<input data-placement="bottom" type="text" name="field1" id="field1" value="" class="form-control" data-rule-required="true" data-msg-required="Provide Field details" aria-required="true">
				</div>
				<div class="margin5px modal-partition">
					<label for="status1">Status</label>
					<select name="status1" id="status1" class="form-control" data-rule-required="true" data-msg-required="Provide Status Field details" aria-required="true">
						<option value="1">Active</option>
						<option value="0">Inactive</option>
					</select>
				</div>
				</span>
			
			<input type="hidden" name="lstItem" id="lstItem" value="0">
			<input type="hidden" name="lstgroupName" id="lstgroupName" value="position">
			<input type="hidden" name="insertRecords" id="insertRecords" value="2,3,4,5,6,7">
			
	<span><span class="twodelete" data-cnt="2"><div class="margin5px modal-partition"><label for="Name">Name</label><input data-placement="bottom" type="text" name="field2" id="field2" class="form-control" data-rule-required="true" data-msg-required="Provide field details"></div><div class="margin5px modal-partition"><label for="status2">Status</label><select name="status2" id="status2" class="form-control" data-rule-required="true" data-msg-required="Provide Status details"><option value="1">Active</option><option value="0">Inactive</option></select></div><input type="button" id="btRemove" rel="position_2" value="X" class="sectionBtn bt"></span><span class="twodelete" data-cnt="3"><div class="margin5px modal-partition"><label for="Name">Name</label><input data-placement="bottom" type="text" name="field3" id="field3" class="form-control" data-rule-required="true" data-msg-required="Provide field details"></div><div class="margin5px modal-partition"><label for="status3">Status</label><select name="status3" id="status3" class="form-control" data-rule-required="true" data-msg-required="Provide Status details"><option value="1">Active</option><option value="0">Inactive</option></select></div><input type="button" id="btRemove" rel="position_3" value="X" class="sectionBtn bt"></span><span class="twodelete" data-cnt="4"><div class="margin5px modal-partition"><label for="Name">Name</label><input data-placement="bottom" type="text" name="field4" id="field4" class="form-control" data-rule-required="true" data-msg-required="Provide field details"></div><div class="margin5px modal-partition"><label for="status4">Status</label><select name="status4" id="status4" class="form-control" data-rule-required="true" data-msg-required="Provide Status details"><option value="1">Active</option><option value="0">Inactive</option></select></div><input type="button" id="btRemove" rel="position_4" value="X" class="sectionBtn bt"></span><span class="twodelete" data-cnt="5"><div class="margin5px modal-partition"><label for="Name">Name</label><input data-placement="bottom" type="text" name="field5" id="field5" class="form-control" data-rule-required="true" data-msg-required="Provide field details"></div><div class="margin5px modal-partition"><label for="status5">Status</label><select name="status5" id="status5" class="form-control" data-rule-required="true" data-msg-required="Provide Status details"><option value="1">Active</option><option value="0">Inactive</option></select></div><input type="button" id="btRemove" rel="position_5" value="X" class="sectionBtn bt"></span><span class="twodelete" data-cnt="6"><div class="margin5px modal-partition"><label for="Name">Name</label><input data-placement="bottom" type="text" name="field6" id="field6" class="form-control" data-rule-required="true" data-msg-required="Provide field details"></div><div class="margin5px modal-partition"><label for="status6">Status</label><select name="status6" id="status6" class="form-control" data-rule-required="true" data-msg-required="Provide Status details"><option value="1">Active</option><option value="0">Inactive</option></select></div><input type="button" id="btRemove" rel="position_6" value="X" class="sectionBtn bt"></span><span class="twodelete" data-cnt="7"><div class="margin5px modal-partition"><label for="Name">Name</label><input data-placement="bottom" type="text" name="field7" id="field7" class="form-control" data-rule-required="true" data-msg-required="Provide field details"></div><div class="margin5px modal-partition"><label for="status7">Status</label><select name="status7" id="status7" class="form-control" data-rule-required="true" data-msg-required="Provide Status details"><option value="1">Active</option><option value="0">Inactive</option></select></div><input type="button" id="btRemove" rel="position_7" value="X" class="sectionBtn bt"></span></span><div class="buttonsPlaceHolder clearbottom">
	
		<button id="getListupdate" class="btn btn-primary" type="submit">Save</button>
	
	</div><span></span>
	</fieldset>
	</form>

Open in new window


you will see it from 2,3,4,5,6,7 because 1 is already created by default is not a part of the cnt

so i delete few of them and the generated html is gonna be like this:

here is the reframed code as i deleted few

<form method="post" name="listSections" id="listSections" class="formpadd" novalidate="novalidate">
	<fieldset><h4 class="sectionTitleh4" id="section-path"></h4>
		
			<div class="floatingLeft"><label class="margin10pxvisiblity">position</label></div>
			<div class="floatingRight"><input type="button" data-coral="0" data-id="position" id="btAdd" value="Add Element" tabindex="-1" class="bt"><input type="button" id="btRemoveAll" value="Remove All" class="bt"></div>
			
				<span class="fixed">
				<div class="margin5px modal-partition aftersect">
					<label for="name1">Name</label>
					<input data-placement="bottom" type="text" name="field1" id="field1" value="" class="form-control" data-rule-required="true" data-msg-required="Provide Field details" aria-required="true">
				</div>
				<div class="margin5px modal-partition">
					<label for="status1">Status</label>
					<select name="status1" id="status1" class="form-control" data-rule-required="true" data-msg-required="Provide Status Field details" aria-required="true">
						<option value="1">Active</option>
						<option value="0">Inactive</option>
					</select>
				</div>
				</span>
			
			<input type="hidden" name="lstItem" id="lstItem" value="0">
			<input type="hidden" name="lstgroupName" id="lstgroupName" value="position">
			<input type="hidden" name="insertRecords" id="insertRecords" value="2,3,4,5,6,7">
			
	<span><span class="twodelete" data-cnt="3"><div class="margin5px modal-partition"><label for="Name">Name</label><input data-placement="bottom" type="text" name="field3" id="field3" class="form-control" data-rule-required="true" data-msg-required="Provide field details"></div><div class="margin5px modal-partition"><label for="status3">Status</label><select name="status3" id="status3" class="form-control" data-rule-required="true" data-msg-required="Provide Status details"><option value="1">Active</option><option value="0">Inactive</option></select></div><input type="button" id="btRemove" rel="position_3" value="X" class="sectionBtn bt"></span><span class="twodelete" data-cnt="4"><div class="margin5px modal-partition"><label for="Name">Name</label><input data-placement="bottom" type="text" name="field4" id="field4" class="form-control" data-rule-required="true" data-msg-required="Provide field details"></div><div class="margin5px modal-partition"><label for="status4">Status</label><select name="status4" id="status4" class="form-control" data-rule-required="true" data-msg-required="Provide Status details"><option value="1">Active</option><option value="0">Inactive</option></select></div><input type="button" id="btRemove" rel="position_4" value="X" class="sectionBtn bt"></span></span><div class="buttonsPlaceHolder clearbottom">
	
		<button id="getListupdate" class="btn btn-primary" type="submit">Save</button>
	
	</div><span></span>
	</fieldset>
	</form>

Open in new window


insert records are still the same, they are not deleted from there
Julian HansenCommented:
This does not look like all your code - where is container defined

 $(container).append('<span class="twodelete" data-cnt="' + cnt + '">

Open in new window


I need to be able to see the jQuery working in the context of the page - and the code posted does not do that - it appears bits are missing.
Gurpreet Singh RandhawaCEOAuthor Commented:
this is my complete code:

var cnt = 1;
var container = $(document.createElement('span'));
var newitems = $(document.createElement('span'));
$('.span.fixed').before(container);
var arry = [], arrys = "";
$('#btAdd').click(function() {
	var groupname = $(this).attr('data-id');
	var isselect = $(this).attr('data-coral');
    if (cnt <= 9999) {
        cnt = cnt + 1;
		arry.push(cnt);
		if(isselect == 1) {
        	$(container).append('<span class="twodelete" data-cnt="' + cnt + '"><div class="margin5px modal-partition"><label for="Name"></label><input data-placement=bottom type=text name="' + groupname + '' + cnt + '"  id="' + groupname + '' + cnt + '" class=form-control data-rule-required=true data-msg-required="Provide field details" /></div><div class="margin5px modal-partition"><label for="status' + '' + cnt + '">Status</label><select name="' + groupname + '' + cnt + '" id="' + groupname + '' + cnt + '" class="form-control" data-rule-required="true" data-msg-required="Provide Status Field details"><option value="1">Active</option><option value="0">Inactive</option></select></div><cfif session.answer["Global Settings.Position.P_CREATE"] IS 0><input type="button" id="btRemove" rel="' + groupname + '_' + cnt + '" value="X" class="sectionBtn bt" /></cfif></span>');
		}else{
			$(container).append('<span class="twodelete" data-cnt="' + cnt + '"><div class="margin5px modal-partition"><label for="Name">Name</label><input data-placement=bottom type=text name="field' + '' + cnt + '"  id="field' + '' + cnt + '" class=form-control data-rule-required=true data-msg-required="Provide field details" /></div><div class="margin5px modal-partition"><label for="status' + '' + cnt + '">Status</label><select name="status' + '' + cnt + '" id="status' + '' + cnt + '" class="form-control" data-rule-required="true" data-msg-required="Provide Status details"><option value="1">Active</option><option value="0">Inactive</option></select></div><cfif session.answer["Global Settings.Position.P_CREATE"] IS 0><input type="button" id="btRemove" rel="' + groupname + '_' + cnt + '" value="X" class="sectionBtn bt" /></cfif></span>');
		}
    }
	arrys = arry.join(",");
	$('#insertRecords').val(arrys);
	$('.buttonsPlaceHolder').before(container);
	$('.buttonsPlaceHolder').after(newitems);
});
$(document).on('click', '#btRemove', function(){
	var item = $(this).closest('.twodelete');
	var v = item.data('cnt');
  	for(var i = arry.length - 1; i >= 0; i--) {
    if(arry[i] === v) {
      arry.splice(i, 1);
      break;
    	}
  	}
  item.remove();
});

Open in new window

Julian HansenCommented:
Ok the problem was that you were not updating the insertRecords input in the delete. The code below is a reworked version of your code with a few changes.
1. The event handlers have been placed inside a document.ready construct
2. I have taken the code for updating insertRecords and placed that in a function which is called from the add and delete event handlers
Working sample with source here
jQuery Code
<script>
function updateInsertRecords() 
{
  arrys = arry.join(",");
  $('#insertRecords').val(arrys);
}

var cnt = 1;
var container = $(document.createElement('span'));
var newitems = $(document.createElement('span'));
$('.span.fixed').before(container);
var arry = [], arrys = "";

$(function() {
  $('#btAdd').click(function() {
    var groupname = $(this).attr('data-id');
    var isselect = $(this).attr('data-coral');
    if (cnt <= 9999) {
      cnt = cnt + 1;
      arry.push(cnt);
      if(isselect == 1) {
        $(container).append('<span class="twodelete" data-cnt="' + cnt + '"><div class="margin5px modal-partition"><label for="Name"></label><input data-placement=bottom type=text name="' + groupname + '' + cnt + '"  id="' + groupname + '' + cnt + '" class=form-control data-rule-required=true data-msg-required="Provide field details" /></div><div class="margin5px modal-partition"><label for="status' + '' + cnt + '">Status</label><select name="' + groupname + '' + cnt + '" id="' + groupname + '' + cnt + '" class="form-control" data-rule-required="true" data-msg-required="Provide Status Field details"><option value="1">Active</option><option value="0">Inactive</option></select></div><cfif session.answer["Global Settings.Position.P_CREATE"] IS 0><input type="button" id="btRemove" rel="' + groupname + '_' + cnt + '" value="X" class="sectionBtn bt" /></cfif></span>');
      }else{
        $(container).append('<span class="twodelete" data-cnt="' + cnt + '"><div class="margin5px modal-partition"><label for="Name">Name</label><input data-placement=bottom type=text name="field' + '' + cnt + '"  id="field' + '' + cnt + '" class=form-control data-rule-required=true data-msg-required="Provide field details" /></div><div class="margin5px modal-partition"><label for="status' + '' + cnt + '">Status</label><select name="status' + '' + cnt + '" id="status' + '' + cnt + '" class="form-control" data-rule-required="true" data-msg-required="Provide Status details"><option value="1">Active</option><option value="0">Inactive</option></select></div><cfif session.answer["Global Settings.Position.P_CREATE"] IS 0><input type="button" id="btRemove" rel="' + groupname + '_' + cnt + '" value="X" class="sectionBtn bt" /></cfif></span>');
      }
    }
	
    $('.buttonsPlaceHolder').before(container);
    $('.buttonsPlaceHolder').after(newitems);
    updateInsertRecords();
  });
  $(document).on('click', '#btRemove', function(){
    var item = $(this).closest('.twodelete');
    var v = item.data('cnt');
    for(var i = arry.length - 1; i >= 0; i--) {
    if(arry[i] === v) {
      arry.splice(i, 1);
      break;
      }
    }
    updateInsertRecords();
    item.remove();
  });
});
</script>

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Gurpreet Singh RandhawaCEOAuthor Commented:
Thanks
Julian HansenCommented:
You are welcome.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.