简体   繁体   English

如何使用javascript或jquery获取HTML表格单元格数据

[英]How to get HTML table cell data using javascript or jquery

I want to extract table cell data using javascript/jquery. 我想使用javascript / jquery提取表格单元格数据。

Table cell structure: 表单元格结构:

<select id="id_item_set-0-type" name="item_set-0-type" onchange="get_names_list(this)" required="required">
    <option value="">SELECT</option>
    <option value="GOLD" selected="selected">GOLD</option>
    <option value="SILVER">SILVER</option>
</select>

jquery Function: jQuery功能:

$( document ).ready(function() {
    var table_id = document.getElementById('item_grid');
    var rows_len = table_id.rows.length-2;
    for(var i=1; i <= rows_len; i++){
        var e = table_id.rows[i].cells[0].firstChild;
        alert(table_id.rows[i].cells[0].innerHTML);
        var item_type = e.options[e.selectedIndex].text;
    }
});

If i use table_id.rows[i].cells[0].innerHTML i get cell html but i want to get selected option value. 如果我使用table_id.rows[i].cells[0].innerHTML我会得到单元格html,但我想获取选定的选项值。 I tried e.options[e.selectedIndex].text but it is throwing error e.selectedIndex is undefined . 我尝试了e.options[e.selectedIndex].text但抛出错误e.selectedIndex is undefined How do i get the selected option value.? 我如何获得选定的期权价值。

Their are actually Two select tags 他们实际上是两个select tags

<select id="id_item_set-0-name" name="item_set-0-name" required="required">
<option value="">SELECT</option>
<option value="1" selected="selected">Name1</option>
<option value="2">name2</option>
..............
</select>

And i have to extract selected values of both. 而且我必须提取两者的选定值。 For example : item_type = "GOLD" and item_name = "name1" Their can be any number of rows that i have to iterate. For example : item_type = "GOLD" and item_name = "name1"它们可以是我必须迭代的任何数量的行。 And have to get values of both item_type and item_name . 并且必须同时获得item_typeitem_name值。

Why are you confusing select tags with table tags? 为什么将选择标签与表格标签混淆?

All you need is: 所有你需要的是:

$('#id_item_set-0-type').find(":selected").text();

add it inside your .ready() function. 将其添加到您的.ready()函数中。

If your ID is dynamically generated at server side and if that is the only select statement you have, use: 如果您的ID是在服务器端动态生成的,并且这是唯一的select语句,请使用:

$('select').find(":selected").text();

try this: 尝试这个:

$( document ).ready(function() {
    var selected_val= $('#"id_item_set-0-type :selected"').val();
    var selected_text=$('#"id_item_set-0-type :selected"').text();
}

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

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