如何防止自动提交表格

时间:2018-07-21 05:17:13

标签: javascript jquery ajax

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

 <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代码进行一次输入?

2 个答案:

答案 0 :(得分:0)

我不确定条形码扫描仪是否输入了“输入密钥”,但是这个怎么样?

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

答案 1 :(得分:0)

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

<input type="hidden" />

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