Home > Software engineering >  onChange not working if first click is on submit
onChange not working if first click is on submit

Time:05-18

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{3}28&amp;action=add_product" method="post" role="form"> 
<input name="formid" type="hidden" 
value="e0cfde314f5da74abe48a886de30aea6c996c334cd40521209a181caba46b763" 
>

<div >
<div >
<div >


<div >

<div >

  <div >
      <label >Name 
</label>
   <div >
       <div id="tagit">
<input name="name" type="text"  id="name">           
           <input name="id[3]" type="hidden"  
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 >
<button data-has-attributes="1" data-in-stock="0" data-product-id="20" 
 
type="submit"> <span  aria-hidden="true"> 
</span> Add To Cart</button><input name="products_id" type="hidden" 
value="20" ></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.

CodePudding user response:

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.

  • Related