Pregunta

I know this shouldn't be this hard, but I need another pair of eyes because I'm beating my head against a wall.

I have a NESTED table with an ID such as:

<table id="dwMeasurements_0">
<tbody>
    <tr id="tDim_0">
        <td colspan="2">
        <strong>Total Wall Length: </strong>
        </td>
        <td>
        <input type="text" id="Msr_0_T1" class="dwInput" value="0"> Inches and </td>
        <td>
        <input type="text" id="Msr_0_T2" class="dwInput" style="margin-left:2px;" value="0"> 16ths</td>
    </tr>
    <tr>
        <td colspan="4">
        <hr>
        </td>
    </tr>
    <tr id="lDim_0_0">
        <td>
            <select id="ItemType_0_0">
                <option>Item Type</option>
                <option>Door</option>
                <option>Window</option>
                <option>Other</option>
            </select>
        </td>
        <td>
        <label>L-Dim: </label>
        </td>
        <td>
        <input type="text" id="Msr_0_0_A1" class="dwInput" value="0"> Inches and </td>
        <td>
        <input type="text" id="Msr_0_0_A2" class="dwInput" style="margin-left:2px;" value="0"> 16ths</td>
    </tr>
//MORE ROWS HERE//
</table>

My jQuery to serialize the text inputs and select elements are as follows:

var MeasureRowCount = $("[id^='MeasureRow_']").length; //Populated by counting parent rows 
var htmlOutput = '';
var rowInputs,rowSelects;
for(var r=0;r < MeasureRowCount;r++){
    rowInputs = $('#dwMeasurements_'+r+' :input').serializeArray();
    rowSelects = $('#dwMeasurements_'+r).find('select').serializeArray();

            $.each(rowSelects, function(i, eSelectItem){
        esName = eSelectItem.name;
        esVal = eSelectItem.value;                

                     htmlOutput += //name and value from above with markup
            }
}

// htmlOutput to DOM here with markup

I've tried multiple methods to collect the input elements and none work. The arrays come up empty. Even though the table is nested, shouldn't it work since I'm directly calling the nested table ID?

¿Fue útil?

Solución 2

The answer wasn't 100% intuitive, but I should've known...

The serializeArray() method defaults to using name:value pairs when collecting elements, and the elements I was collecting didn't have any "name" attributes, only id's. Once I added names, the arrays populated as desired.

Otros consejos

This code:

for(var r=0;r < MeasureRowCount;r++){
    rowInputs = $('#dwMeasurements_'+r+' :input').serializeArray();

Will overwrite the value of rowInputs every time it loops.

Try using jQuery.merge to combine them instead:

var rowInputs=[],rowSelects=[];
for(var r=0;r < MeasureRowCount;r++){
    $.merge(rowInputs, $('#dwMeasurements_'+r+' :input').serializeArray());
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top