使用jquery获取表中具有相同Id的文本框的值?

时间:2012-12-07 19:26:11

标签: jquery html

<table class="csstable">
    <tr>
       <td>
       <textarea id="txtOption" rows="2" cols="30">hi this is me!!!</textarea>
       </td>
    </tr>
    <tr>
       <td>
       <textarea id="txtOption" rows="2" cols="30">hi this is you!!!</textarea>
       </td>
    </tr>

我做了什么:

  $(".csstable").each(function(){
       alert($("#txtOption").val());
      });

我在两个时间都得到文本区域的第一个值,即嗨这是我!!!

3 个答案:

答案 0 :(得分:1)

您不能在页面上拥有两个具有相同值的ID,这是无效的。

ID必须是唯一的。

尝试使用类(或其他内容)来代替

<textarea class="txtoption1" rows="2" cols="30">option1</textarea>

<textarea class="txtoption2" rows="2" cols="30">option2</textarea>

答案 1 :(得分:1)

如果您有多个具有相同ID的元素,则只会匹配第一个元素。

因此,请使用class代替,按标记名称获取或使用唯一ID。

然后你可以通过以下方式获得它的价值。

$(".csstable .myTextareaClass").each(function(){
    alert($(this).val());
});

$(".csstable textarea").each(function(){
    alert($(this).val());
});

alert($('#textareaId').val());

答案 2 :(得分:0)

每个ID必须唯一,因为某种原因称为id

相反,您应该使用class属性

<textarea class="txtOption" rows="2" cols="30">hi this is you!!!</textarea>

您可以阅读更多相关信息 here