Javascript - 在表格中获取选定的选项

时间:2014-12-22 11:14:32

标签: javascript html

我有一个HTML表格,我希望在td的列表中获得一个选定的值。

我这样做:

var table = document.getElementById('ZZ');
    for (var r = 0, n = table.rows.length; r < n; r++) {
        for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
            var type =table.rows[r].cells[11].innerHTML;
            alert(type);
        }
    }

我在警报框中得到了这样的结果

<SELECT id="" onchange=''... <OPTION value=1>A</OPTION><OPTION selected=2>B</OPTION></SELECT>

我想得到&#39; B&#39;在变种中 我怎么能完成这个?

4 个答案:

答案 0 :(得分:2)

既然你说你得到了你得到的结果,你可以使用Element.querySelector使用css选择器来定位元素。

var type = table.rows[r].cells[11].querySelector("[selected]").innerHTML;

请注意,我使用的是innerHTML,因为textContentinnerText之间存在一些差异,并且由于<option>不能包含任何html这一事实。

答案 1 :(得分:1)

**

  

如果您的选择选项存在于表的td的内部子项中   而您想获得价值,这可能会帮助您。对我有用

**

**HTML**

<table class="table table-borderless" id="all_table_hour">
  <tbody class="table-hours-record">
  <tr data-mytr_id=1 class="table-rowclass1">
    <td>Time</td>
    <td data-mytd1_id=1 class="table-rowtd1class1">
      <div class="time-slot">
        <span >
          <select class="hour_selected_from_all" id="hour_selected_from_all1">    
            <option selected="selected" value="00:00">0 hour</option>
            <option value="01:00">1 hour</option> 
          </select>
        </span>
      </div>
    </td>
    <td >
      <div class="time-slot">
        <input placeholder="$10.00">
      </div>
    </td>
  </tr>

  </tbody>
</table>

**

  

CODE JS

**

var testTable = document.getElementById('all_table_hour');

for (i = 1; i < testTable.rows.length; i++) {

    var recordcells = testTable.rows.item(i).cells;
    for (var j = 0; j < recordcells.length; j++) {
        record = recordcells.item(j).getElementsByTagName("select")[0].value
        //Now you can add this record as per your required format (list or in json format)
    }
}

答案 2 :(得分:0)

 html:

    <SELECT id="orange" onchange=''... >
       <OPTION value=1>A</OPTION>
       <OPTION selected=2>B</OPTION>
    </SELECT>

    script:

   var allDropdown =  document.getElementsByTagName("select");
   allDropdown[0].value;
  allDropdown[1].value;

/ ********************************************** ************ /

for(var item in allDropdown ){
      alert(allDropdown[item].value)
    } 

答案 3 :(得分:-1)

As in your code you are able to get object of TD then you can use "Find" function to find select and take selected option out from the select.
.find("select") will give you select jquery object and then through sudo code used :selected" you can find selected option from list.It will  return you "B".
var table = document.getElementById('ZZ');
for (var r = 0, n = table.rows.length; r < n; r++) {
	for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
		var type =table.rows[r].cells[11].find("select")**.find(":selected").text()**;
		alert(type);// B
		
	}
}

Hope this will help