简体   繁体   English

HTML表到JavaScript数组的特定列

[英]Specific columns of a HTML table to JavaScript array

I need help on storing two columns of a html table to a Javascript array. 我需要有关将html表的两列存储到Javascript数组的帮助。 I create the table dynamically using php. 我使用php动态创建表。 following is my php code; 以下是我的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;
}

This populates the html table with relevant 'id','desc' etc from the database. 这将用数据库中的相关“ id”,“ desc”等填充html表。 Then it writes radio buttons with a unique tag name for each of them. 然后,它会为每个单选按钮编写一个唯一的标签名称。 The result looks like following; 结果如下: 在此处输入图片说明

I want to store the id in the first column and its relevant rating (ie. 1,2,3,na) to a Javascript array. 我想将第一列中的ID及其相关的等级(即1,2,3,na)存储到Javascript数组中。

Please help. 请帮忙。

If you have jQuery already included or free to use it you can try the following code: 如果您已经包含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);

Demo 演示版

If not it will be little more complex to iterate over DOM-elements but still doable ) 如果不是这样,遍历DOM元素将稍微复杂一些,但仍然可行)

Place the whole table into a form so 将整个桌子摆成表格

<form id="form">
    <table>
        .. etc ..
    </table>
</form>

And then serialize the form on click using $('#form').serialize(); 然后使用$('#form').serialize();单击序列化表单$('#form').serialize();

Fiddle (forked from pxx): http://jsfiddle.net/B5fKm/ 小提琴(从pxx分叉): http : //jsfiddle.net/B5fKm/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM