日期:2014-05-16  浏览次数:20412 次

JavaScript知识拾遗:如何获取动态表格中select控件的选中值

??? 有很长一段时间没做Web前端开发了,这几天工作中做一个小项目需要做几个Web页面,其中涉及到一些JS的知识,很多都不怎么熟悉了,花了不少时间才完成工作需求。因此写几篇blog记录下来。

??? 在一个Web页面中,有一个表格,其是根据Struts2的Iterator标签动态生成的,改表格的Html代码如下:

      <table width="550" id="serverTab" border="1" cellpadding="0" cellspacing="0" align="left">
        <tr bgcolor="#0099CC">
        <td width="10%"><div align="center"> ID</div></td>
        <td width="25%"><div align="center"> Host</div></td>
        <td width="10%"><div align="center"> Port</div></td>
        <td width="5%"><div align="center"> Interval(s)</div></td>
        <td width="35%"><div align="center"> Comment</div></td>
        <td width="20%"><div align="center"> Need Monitoring?</div></td>
        </tr>
        <s:iterator value="serverListByType" id="serverList"    status="status" > 
        <tr>
        <td><div align="left"><s:property value="id"/></div></td>
        <td><div align="left"><s:property value="host"/> </div></td>
        <td><div align="left"><s:property value="port"/></div></td>
        <td><div align="left"><s:property value="interval"/> </div></td>
        <td><div align="left"><s:property value="comment"/></div></td>
        <td><div align="left">
        <select style='width:95px' > 
        <s:if test="0==need">
	        <option  value='0' >No</option> 
	        <option  value='1'>Yes</option> 
	    </s:if>
	    <s:else>
	    	<option  value='1' >Yes</option> 
	        <option  value='0'>No</option> 
	    </s:else>
	    </select>
        </div></td>
        </tr>

?我要获取该表格中,每行select控件的选中值,由于该表格是动态生成,因此不便制定select的ID及name属性。

开始我试图通过以下代码来获取各行的select选中值:

    var tab=document.getElementById("serverTab");
          var ServerLists="";
                  
          for(var rowIndex=1;rowIndex<tab.rows.length;rowIndex++)
          {
            	  for(var childIndex = 0; childIndex<tab.rows[rowIndex].cells[5].children.length;childIndex++)
                  {
                        var cb= tab.rows[rowIndex].cells[columnIndex].children[childIndex];
                        var selectvalue = cb.options[cb.selectedIndex].value;
                         ServerLists+=selectvalue ;
                  }
          }

?结果发现cb.options[cb.selectedIndex].value这句话提示错误,根本无法识别options,即在上段代码中,cb根本没有被识别成一个select对象。

在试过其它多种方法后,终于找到了一个正确的获取select值的方法。代码如下:

var selectinput=tab.getElementsByTagName("select");
input[rowIndex].options[input[rowIndex].selectedIndex].text
input[rowIndex].options[input[rowIndex].selectedIndex].value

?通过上面的代码就可以拿到动态表格中各行select的值。

?

?

也许是JS水平太差了,纠结了一上午才找到这个。。。不容易啊。

?


???????