【问题标题】:Without text, Jquery prevents input box trigger but not textarea trigger没有文本,Jquery 防止输入框触发但不是 textarea 触发
【发布时间】:2017-06-21 12:32:09
【问题描述】:

我的输入框使用占位符文本和 jquery 来确保在我添加文本(即不是占位符文本)之前它不会触发。我想用文本区域替换输入框,但无法让 jquery 工作。使用下面的文本区域,无论我是否在文本区域中输入,都会触发提交按钮。

<div class="RepForm-loggedin" >
  <form name="RepForm" method="POST" action="<?php echo $this->newReply;?>">
    <table name="RepFormTable" style="width:100%">
      <tr>
        <td style="width:100%">

    //CURRENT INPUT BOX
        <input type="text" rows="8"  id="repContent" class="inputbox inputbox-title placeholder-soc-med" name="repContent" placeholder="Ask a question . . ."/>

    //DESIRED REPLACEMENT TEXT AREA
        <textarea type="text" rows="8"  style="max-width:600px; width:100%" id="repContent" class="inputbox inputbox-title placeholder-soc-med" name="repContent" placeholder="Ask a question . . ."></textarea>

        </td>
       </tr>
       <tr>
         <td style = "text-align:right;">
             <input type="submit" value="Submit" id="sendComment" class="dgrey-button">
         </td>
       </tr>
    </table>
  </form>
</div>

<script type="text/javascript">
        $(document).ready(function(){
            $('#sendComment').attr('disabled',true);
            $('#repContent').keyup(function(){
                if($(this).val().length !=0)
                    $('#sendComment').attr('disabled', false);
                else
                    $('#sendComment').attr('disabled',true);
            })
        });
    </script>

【问题讨论】:

    标签: javascript php jquery textarea inputbox


    【解决方案1】:

    你复制了id="repContent"

    你的输入框也有这个ID。因此,当您使用 $('#repContent') 选择您的元素时,它只返回您的输入字段。

    只需从&lt;input /&gt; 中删除此属性,您的代码就会运行。

    工作小提琴:https://jsfiddle.net/mrlew/7o493syd/1/


    您可能会问:为什么$('#id') 不会选择所有具有此 ID 的元素?

    首先,文档中只能有一个具有相同 ID 的元素。来自HTML specification

    id = 此属性为元素分配名称。此名称在文档中必须是唯一的。

    然后,当您使用 jQuery 按 id 选择时,它将只返回第一个匹配项(因为它在内部使用 document.getElementById())。来自docs

    每个 id 值在文档中只能使用一次。如果超过 一个元素被分配了相同的 ID,使用该 ID 的查询 只会选择 DOM 中第一个匹配的元素。这种行为 然而,不应依赖;一份文件有多个 使用相同 ID 的元素无效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-23
      • 2013-05-01
      • 2011-03-08
      • 1970-01-01
      • 1970-01-01
      • 2010-10-22
      • 1970-01-01
      相关资源
      最近更新 更多