简体   繁体   中英

How to prevent auto form submit

I have the following input box which takes input from barcode scanner.

 <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>

After getting the input from barcode it does following operation (from the input it checks value from database and add to row)

$( "#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; 
              } 

        });

});

But the problem the form get auto submit ie, i can't add more than one value in the table. How do i prevent the form automatic submit so that more that one input can be taken with the above ajax code?

I'm not sure if the barcode scanner put the "enter key", but how about this one?

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

IMO, the easiest way is to add a hidden input

<input type="hidden" />

browser will auto submit if there is one input in a form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM