bccarlso bccarlso - 10 days ago 4x
jQuery Question

Getting text from a cell using the each function on checked checkboxes

I have a list of states, each with some data associated with it, displayed in a table, with a checkbox next to each state. I have it successfully computing the sum of input values of all checked states, but I need to store the additional data for each state in a 3D array so that I can display it later in the form's summary, showing the user just the states they selected. I have found a few solutions, but haven't been able to get any to work for my setup. This is what I have so far (hoping I'm not leaving any important code out):

var returnDb = new Array();
var inc = 0;
var returnState = '';
var returnNum = '';
var returnEmail = '';
$("input:checked").each(function() {
var value = 1*$(this).attr("title");
var value_vendors = 1*$(this).attr("title");

// These are causing my script to stop
returnState = ''. $(this).closest('tr').find('td:eq(1)').text();
returnNum = ''. $(this).closest('tr').find('td:eq(2)').text();
returnEmail = ''. $(this).closest('tr').find('td:eq(3)').text();

returnDb[inc] = [['' . returnState, '' . returnNum, '' . returnEmail]];

total += parseInt(value);
vendors += parseInt(value_vendors);


When I comment out the three lines that cause my script to stop, everything works fine. Any idea what I'm doing wrong or if there is a better approach to this?


In javascript you concatenate strings using +, but you don't even need that here. I would also use parseInt to extract the values. Total and vendors also need to be initialized. Finally, each will give you the index as a argument so there's no need for your counter.

Edit: Note I changed the assignment to the returnDb array. Your original assigns an array containing an array of values to each array element in returnDb. The new code assigns an object with three properties (state, num, email) to each element in returnDb. Your original may have been correct -- I don't know how you are using it -- but I think the object approach is more usable in most instances.

var returnDb = new Array();         
var returnState = '';     
var returnNum = '';     
var returnEmail = ''; 
var total = 0;
var vendors = 0;    
$("input:checked").each(function(i) {     
    var value = parseInt( $(this).attr("title") );     
    var value_vendors = parseInt( $(this).attr("title") );     

    // These are causing my script to stop     
    returnState = $(this).closest('tr').find('td:eq(1)').text();     
    returnNum = $(this).closest('tr').find('td:eq(2)').text();     
    returnEmail = $(this).closest('tr').find('td:eq(3)').text();     

    //returnDb[i] = [[returnState, returnNum, returnEmail]];   
    returnDb[i] = { state: returnState, num: returnNum, email: returnEmail };  

    total += value;     
    vendors += value_vendors;