【问题标题】:Access value of textarea in jQuery with multiple same Id's?具有多个相同ID的jQuery中textarea的访问值?
【发布时间】:2012-06-12 10:33:56
【问题描述】:

我的页面中有多个名为“post”的 div 标签,我想做的是在提交点击时在服务器上发布数据。我无法在我的 jquery 方法 commentPost() 中检索 textarea "commentText" 的值。

<div id="post">
  <br>topic containtment is here
  <form name="postComment" id="commentForm" action="javascript:void(0);" method="post"    
   target="_top" onsubmit="return commentPost();">
    <textarea name="comment" id="commentText" cols="10" rows="3" accesskey="1">
    </textarea><br>
    <input type="submit" name="submit" id="commentpost" value="Submit" accesskey="2">
   </form>
</div>

jQuery 方法

function commentPost()
{
    alert("Inside commentpost");
        //how to get value of commentText
    var comment=("form > commentText").val(); //<--not working
    alert(comment);
    //further code to be written
}

注意:页面中有多个div post标签。

如何获取textarea的值??

【问题讨论】:

  • “页面中有多个 div 帖子标签”... 那么您的标记无效。改为将其更改为类名。 ID 值必须是唯一的。
  • commentPost 方法有语法错误。应该是 var comment = $('form &gt; #commentText').val() 您缺少 $$sign 函数和指定类的主题标签。

标签: jquery function html jquery-mobile textarea


【解决方案1】:

如果您的文档中有一个值为“commentText”的 id,那么您的函数应如下所示:

function commentPost()
{
    alert("Inside commentpost");
        //how to get value of commentText
    var comment=("form > #commentText").val(); //<--not working
    alert(comment);
    //further code to be written
}

如果您有更多带有此 ID 的标签,则您的标记无效,您应该在标记中将 id="commentText" 更改为 class="commentText"。在这种情况下,您的函数应如下所示:

function commentPost()
{
    alert("Inside commentpost");
        //how to get value of commentText
    var comment=("form > .commentText").val(); //<--not working
    alert(comment);
    //further code to be written
}

当这可行时,不要忘记从您的函数中删除警报。

【讨论】:

    【解决方案2】:

    not valid HTML 的多个元素具有相同的ID

    如果你解决了这个问题,那么你的 jQuery 问题将被间接解决。

    【讨论】:

      【解决方案3】:

      id 必须能够识别页面上的唯一元素。

      通常,您尝试做的事情可以通过使用class 来解决:

      <textarea name="comment" class="commentText" cols="10" rows="3" accesskey="1">
      </textarea><br>
      

      然后,使用$("form &gt; .commentText")

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-31
        • 2018-08-02
        • 2017-06-09
        • 1970-01-01
        • 2012-01-19
        • 1970-01-01
        相关资源
        最近更新 更多