[英]Specific columns of a HTML table to JavaScript array
我需要有關將html表的兩列存儲到Javascript數組的幫助。 我使用php動態創建表。 以下是我的PHP代碼;
$inc = 1;
foreach($result as $element) {
echo "<tr><td>".$element['qs_id']."</td>";
echo "<td>".$element['qs_desc']."</td>";
echo "<td><input type=\"radio\" name=\"select".$inc."\" value=\"0\" ";
if($element['qq_rate'] == '0') echo "checked=\"checked\"";
echo "></input></td>";
echo " <td><input type=\"radio\" name=\"select".$inc."\" value=\"1\"";
if($element['qq_rate'] == '1') echo "checked=\"checked\"";
echo "></input></td>";
echo " <td><input type=\"radio\" name=\"select".$inc."\" value=\"2\"";
if($element['qq_rate'] == '2') echo "checked=\"checked\"";
echo "></input></td>";
echo " <td><input type=\"radio\" name=\"select".$inc."\" value=\"3\"";
if($element['qq_rate'] == '3') echo "checked=\"checked\"";
echo "></input></td>";
echo " <td><input type=\"radio\" name=\"select".$inc."\" value=\"na\"";
if($element['qq_rate'] == '') echo "checked=\"checked\"";
echo "></input></td>";
echo "</tr>";
$inc = $inc +1;
}
這將用數據庫中的相關“ id”,“ desc”等填充html表。 然后,它會為每個單選按鈕編寫一個唯一的標簽名稱。 結果如下:
我想將第一列中的ID及其相關的等級(即1,2,3,na)存儲到Javascript數組中。
請幫忙。
如果您已經包含jQuery或可以免費使用它,則可以嘗試以下代碼:
var data = [];
$('table tr').each(function(){
var row = $(this);
var id = row.find('td:first').text();
if ($.isNumeric(id)) {
var selectedRadio = row.find(':radio[name=select' + id + ']:checked');
data.push([id, selectedRadio.val()]);
}
});
alert(data);
如果不是這樣,遍歷DOM元素將稍微復雜一些,但仍然可行)
將整個桌子擺成表格
<form id="form">
<table>
.. etc ..
</table>
</form>
然后使用$('#form').serialize();
單擊序列化表單$('#form').serialize();
小提琴(從pxx分叉): http : //jsfiddle.net/B5fKm/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.