【问题标题】:Two form submit on same page, only the first one works. JQuery两个表单在同一页面上提交,只有第一个有效。 jQuery
【发布时间】:2013-06-18 10:20:50
【问题描述】:

我在一个页面上提交了两个表单,它们都在做同样的事情。

一个在工具栏/导航栏上,另一个在主页上。
我遇到的问题是,一旦我在工具栏上添加了表单,主页上的表单在触发时就永远没有搜索值,如果我注释掉工具栏中的表单,那么主页就有了值。

//Toolbar submit
<form>
  <div class="input-append">
    <input type="text" class="span3" placeholder="Enter name" />
    <button type="submit" class="btn-u">Go</button>
   </div>
 </form>

// Main page submit
<form class="form-inline margin-bottom-5">
  <div class="input-append">
    <input type="text" class="input-xxlarge" placeholder="Enter class name">
    <button type="submit" class="btn-u">Go</button>
  </div>
</form>

//JavaScript/JQuery
$("form").submit(function (e) {

  var searchTerm = $("input:first").val();
  if (searchTerm === '') {
    // This part of the code is reached for the second submit,
    // I have tried using id on the submit but have the same result
  }

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    更改下面的内容,此时它正在寻找页面上的第一个输入,这将在实际提交的表单中寻找第一个输入。

    var searchTerm = $("input:first").val();
    

    var searchTerm = $(this).find("input:first").val();
    

    【讨论】:

      【解决方案2】:

      您正在寻找var searchTerm = $("input:first").val(); 没有任何迹象表明您正在寻找提交表单中的第一个输入。在这里,您正在寻找页面第一个表单的第一个输入。将其替换为var searchTerm = $(this).find("input:first").val();

      编辑:嗬,我回答太慢了……嗯,至少它确认了解决方案。

      【讨论】:

        【解决方案3】:

        使用“this”确保您正在寻找您提交的表单中的第一个输入:

        $("form").submit(function (e) {
        
           var searchTerm = $(this).find("input:first").val();
           if (searchTerm === '') {
              // This part of the code is reached for the second submit,
              // I have tried using id on the submit but have the same result
           }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-25
          • 2017-03-21
          • 2016-07-31
          • 2012-11-29
          • 1970-01-01
          • 2022-01-14
          相关资源
          最近更新 更多