I am hoping someone can help me attain better performance and better ways of writing this script. Any help would be awesome!
Overall Goal: I have a dropdown that allows someone to select an option from it. It will add that record to the table below, and then the option will be removed. If they delete that row in the table, it then adds that option back to the dropdown.
$(function() {
$('#addResource').on('change', function(){
var $selectBox = $(this),
oID = $selectBox.val(),
oText = $selectBox.children(':selected').text(),
url = '/admin/contacts/json',
oSize = $selectBox.children('option').size()
noResources = '<tr class="no-resources"><td colspan="5">No Resources.</td></tr>';
//if select box out of options lets hide it
if((oSize-1) == 1) {
$selectBox.hide().parent().append('<div class="alert alert-info">No More Contacts Available</div>');
}
// lets remove the selected option
$selectBox.children(':selected').remove();
$selectBox.children(':first').attr('selected','selected');
// lets get the contact to add to the table
$.post(url, { id: oID },function(data){
var tableRow = "<tr class='resource_"+data.id+"'><input type='hidden' value='"+data.id+"' name='resouces[]'><td class='name'>"+data.name+"</td><td>"+data.phone+"</td><td>"+data.email+"</td><td>$"+data.rate+"</td><td><a href='#' title='Remove Resource' class='remove_"+data.id+"' data-id='"+data.id+"'><i class='icon-trash'></i></a></td></tr>",
table = $("#resourcesTable tbody");
table.find('tr.no-resources').remove();
table.append(tableRow);
cssClass = '.remove_'+data.id;
table.on('click',cssClass, function(e){
var $trash = $(this),
rowId = $trash.attr('data-id');
// open confirm modal window
modalMsg('Are you sure you wish to delete '+data.name+' as a resource?','',function(result){
// remove deleted row
$(".resource_"+rowId).fadeOut(function(){
var size = table.find('tr').size(),
name = $(this).find('.name').text();
$selectBox.append("<option value='"+rowId+"'>"+name+"</option>"); // add option back to dropdown
$(this).remove(); // remove the table row when deleted
if((size-1) == 0 ){ // if no more talbe rows put back no resources message
table.append(noResources);
}
});
// need to
})
e.preventDefault();
});
// need to add input fields to post to save to database
}, "json" );
}); // end on change
});