Problem with deleting a recipient object from an array by the recipient's ID value

Hi Guys,

I have a form where recipients can be added to the group of recipients http://screencast.com/t/H1QFdzLBg8. I use two inputs for gathering names and emails and the <ul> highlighted in red where I add recipients as <li>. Adding and deleting recipient functions are working fine so far. After recipients are gathered I need to send them via ajax. I can’t take recipients from the <ul> and store them in a variable with the form submit, which would be logical because I trim strings that are too long. You can see on the screenshot fourth recipient has name and email strings to long.

I decided to add recipients to an array at the same time when I add them to the recipients group. That’s fine. However I need to delete them from the array at the same time when I delete them from the recipient group. I thought I might add an ID to every recipient <li> and delete an item from the array by the objects ID. That didn’t work because if I delete the first object from the array with an ID 0 the second object’s ID will be changed to 0, where the recipients ID from the recipients group remains the same value regardless of it’s position.

The other option that I considered was to add an ID property to every recipient. I can find that ID but how will I delete the rest of the objects properties such as a name and an email.

Creating a recipient in the recipient group

var recipients = [];
	var i = 0;
	function createRecipient(name,email) {
		recipients.push({ID:'rec_'+i,'recipients_name':name,'recipients_email':email});
		if (name.length > 24) {name = name.substr(0,24) + '...'};
		if (email.length > 25) {email = email.substr(0,25) + '...'};
		$("#share_via_email .recipient_group").append("<li id='rec_"+i+"' class='recipient' style='display:none'><span class='avatar'></span><h3 class='recipient_name'>"+name+"</h3><span class='recipient_email'>"+email+"</span><a href='#' class='recipient_close'></a></li>");
		$("#share_via_email .recipient_group .recipient:last-child").fadeIn(200);
		i++;
	}

Delete a recipient from the recipients group

$("#share_via_email .recipient_group").on("click", ".recipient_close", function() {
		$(this).parent(".recipient").fadeOut(200, function() {
			$(this).remove();
		});
		numberOfRecipients --;
		i--;
	});

Do you have any ideas? Thanks

Hi Yarik,

Instead of an array, you could use an object to store the data as key/value pairs, like this:

recipients = {};

// Add a recipient
recipients[email] = name;

//Removing a recipient
delete recipients[email];

As email addresses over 25 chars in length get truncated for display, you can’t use that value when you want to remove a recipient from the list, so you could store the original, unaltered email on the list element as a data attribute.

That makes perfect sense. Thanks so much!