'onChange not working if first click is on submit

Not sure if this is something that can be fixed or if I need to look at other options but here is my issue.

I have a text input box and when text is entered it triggers an ajax function and writes data to a database. This works fine if I write in the box then click/tab out of the box. There is also a submit button on the page, if I type in the input box and click the button the ajax isn't triggered.

<form name="cart_quantity" 
action="http://127.0.0.1/360v3/product_info.php? 
products_id=20%7B3%7D28&amp;action=add_product" method="post" role="form"> 
<input name="formid" type="hidden" 
value="e0cfde314f5da74abe48a886de30aea6c996c334cd40521209a181caba46b763" 
class="form-control">

<div class="row is-product">
<div class="col-sm-12 cm-pi-modular">
<div class="row">


<div class="col-sm-4">

<div class="col-sm-12 text-right mt-2 pi-text-input">

  <div class="form-group row">
      <label class="col-form-label col-sm-3 text-left text-sm-right">Name 
</label>
   <div class="col-sm-9">
       <div id="tagit">
<input name="name" type="text" class="form-control" id="name">           
           <input name="id[3]" type="hidden" class="form-control" 
id="input_3" value="30">
       </div>
      </div>
      </div>
</div>

<script type="text/javascript" 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> 
<script type="text/javascript">
$( document ).on( 'blur',  '#tagit #name', function(){
    name = $('#name').val();
pID = $('#pID').val();
$.ajax({
    type: "POST", 
    url: "ext/scripts/textAttribute.php", 
    data: "name=" + name + "&pID=" + pID + "&type=insert",
    cache: true, 
    success: function(data){
      $("#input_3").val(data);
    }
  });
  
});
</script>

<div class="col-sm-12 pi-buy-button mt-2">
<button data-has-attributes="1" data-in-stock="0" data-product-id="20" 
class="btn btn-success btn-block btn-lg btn-product-info btn-buy" 
type="submit"> <span class="fas fa-shopping-cart" aria-hidden="true"> 
</span> Add To Cart</button><input name="products_id" type="hidden" 
value="20" class="form-control"></div>

  </div></div>

</div>
</div>

</form>

Contents of textAttribute.php has been omitted as I do not believe it is relevant to the issue.

So far I have changed the onChange to onBlur with the same issue and onInput however this triggers the function for each keystroke.

What am I missing?

UPDATE

I have changed the onChange to onInput and am now looking at ways to limit the number of times it runs to just one using timers or similar.



Solution 1:[1]

Hi if you are looking on how to limit it, there are so called "debounce" functions.

Basically you can limit how fast some actions are going to be processed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Curky