【问题标题】:How to prevent auto form submit如何防止自动提交表单
【发布时间】:2018-07-21 20:16:53
【问题描述】:

我有以下输入框,它接受条形码扫描仪的输入。

 <form class="m-form m-form--fit m-form--label-align-right" method="post" action="{{ url('updateInvoice') }}" id="invoice_update">
    <div class="form-group m-form__group">
       <label for="exampleInputEmail1">Search by item name or barcode</label>
       <input type="text"  autofocus class="form-control m-input" id="productSearch"  placeholder="Item name">              
    </div>
     <button type="submit" name="pdf" class="btn btn-success">Update & print
     </button>
</form>

从条形码获取输入后,它会执行以下操作(从输入中检查数据库中的值并添加到行中)

$( "#productSearch" ).change(function(event) {
    event.preventDefault();

  $.ajax({
          type: "get",
          context: this,
          url: "{!! asset('searchByProductName') !!}",
          dataType: 'json',
          data: { name:this.value },
          success: function(response)
            {
              if ($('#' + response.id).length !== 0)

              { $(this).val("").focus(); return false; }

             var markup = "<tr id="+response.id+"><input type='hidden' name='product_id[]'  value="+response.id+"><td><i class='flaticon-delete-1 delete-row' onclick='deleteRow(this)'></i></td><td>"+response.product_name+"</td><td>"+response.product_unit_price+"</td><td><input type='text' name='quantity[]' class='quantity' value='1'></td><td class='total'>"+response.product_unit_price+"</td><td>"+response.notes+"</td></tr>";  
              $("table tbody").append(markup); 
              $(this).val("").focus(); return false; 
              } 

        });

});

但是表单自动提交的问题是,我不能在表中添加多个值。如何防止表单自动提交,以便使用上述 ajax 代码进行更多的输入?

【问题讨论】:

  • 从按钮中删除type="submit"并添加onclick javascript listner
  • @DeepakPatel 这不是正确的选择
  • 你的意思是你不能在表中添加多个值?
  • 每当输入框填满条码扫描器。表单被提交。这就是为什么我不能从上面的输入框中添加更多内容

标签: javascript jquery ajax


【解决方案1】:

我不确定条形码扫描仪是否输入了“输入键”,但是这个呢?

$("#form-id").on("submit", function(e) {
    if ($("#input-id(productSearch)").is(":focus")) {
        e.preventDefault();
    }
});

【讨论】:

    【解决方案2】:

    IMO,最简单的方法是添加隐藏输入

    <input type="hidden" />
    

    如果表单中有一个输入,浏览器将自动提交。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-20
      • 2012-05-26
      • 1970-01-01
      • 2018-10-07
      • 2016-06-30
      相关资源
      最近更新 更多