2012-12-10 136 views
0

我有一個表格的形式。jquery選擇一個項目

<form > 
    <div> 
    <table> 
<tr>   
     <td > <input type="text" id="slno1" size="25" value="10" /> </td>  
     <td > <input type="text" id="data" size="10" value="this is a test" /> </td>  
     <td > <input type="radio" value="" id="edit1" name="sample" /> </td>  

    </tr> 
    <tr>   
     <td > <input type="text" id="slno2" size="25" value="10" /> </td>  
     <td > <input type="text" id="data1" size="10" value="this is a test1" /> </td>  
     <td > <input type="radio" value="" id="edit1" name="sample" /> </td>  
    </tr> 
    </table> 
    <input type="submit" id="mysu1" Value="submits" /> 
    </div> 
    </form> 

因爲當用戶選擇一個單選按鈕的行時,我需要該行上的所有數據。 所以,我們做的:

var theSelectedRadioButton = theForm.find('input[name="sample"]:checked'); 

我怎樣才能在TD的所有相應的值。

回答

1

您可以使用closest單選按鈕,找到tr它在,然後children找到所有的td s表示行中:

var tds = theSelectedRadioButton.closest('tr').children('td'); 

然後從td s擷取的信息,可能在使用eachmap的循環中。你還沒有說哪裏的信息,但對於例如,如果你希望自己的HTML:

var tdhtml = theSelectedRadioButton.closest('tr').children('td').map(function(td) { 
    return $(this).html(); 
}).get(); 

...結果字符串數組中tdhtml包含每個td的HTML。 (注意在結束時容易錯過呼叫getmap返回即使它的內容不是DOM元素jQuery對象,get將其轉換成正常陣列。)

可替換地,如果信息被存儲在在td小號data-*屬性(在這個例子中data-foo):

var tddata = theSelectedRadioButton.closest('tr').children('td').map(function(td) { 
    return $(this).attr('data-foo'); 
}).get(); 
+0

謝謝我也更新了表單數據。當我保持警覺時,我得到:tds作爲對象對象..比這更容易 –

+1

@TheLearner:對,'tds'是一個對象。它是一組匹配的'td'元素的jQuery包裝器。我向你展示瞭如何從這些元素中提取信息(作爲數組)。強烈建議不要使用'alert'這個東西。所有主流瀏覽器都至少內置了一個體面的調試器:http://blog.niftysnippets.org/2011/03/no-excuse.html使用適當的工具,您可以檢查內容'tds' /'tdhtml' /'tddata'甚至(有幾個)使用交互式代碼來找出如何處理它。 –

1
var theSelectedRow = theSelectedRadioButton.closest('tr'); 

應該給你行,從那裏你可以在該行中訪問數據。

另外:你可以將數據處理函數綁定到單選按鈕,那麼你不需要「找到」它。

1

jsFiddle Demo

當目標輸入字段的值發生變化,你可以找到使用.closest()找到合適的行,然後收集每個孩子的值到一個新的對象。

$(theForm).find('input[name="sample"]').change(function() { 

    var vals = $(this).closest('tr').children('td').map(function() { 
     return $(this).find('input').val(); 
    }).toArray(); 
});