how to differentiate between javascript submit and

2019-06-19 13:00发布

问题:

how to differentiate between javascript triggered submit and manually clicking form submit
sample code below

 function myfunction()
 {
    document.getElementById("id_searchform").submit();
    return true;
 }

form:

<div class='row'>
   <div class='col-md-4'>
      <div class='clszipcode' ><span>Enter Zipcode</span></div>
   </div>
   <div class='col-md-4'>
      <div class='clstxtzipcode' ><input type="text" name="zip_code" id="txtZipcode"></div>
   </div>
   <div class='col-md-4'>
      <div class='clsbtnzip' ><input type="submit" name="submit" id="btnSearch" value="Search" class="button_example"  ></div>
   </div>
</div>
<a href="#"  onclick="return myfunction();" >click to submit</a>

回答1:

Let me see if I understand:

  1. You want to detect whether the user clicked the link to submit the form.
  2. You want to detect if the user clicked the submit button to submit the form.
  3. You have another function called validate() which will use this information in some way.

If this is the case, consider using a variable to store whether the link was clicked before triggering the form to submit.

  1. Initialize global variable wasClicked to false
  2. When link is clicked set wasClicked to true
  3. Trigger form submit after wasClicked is set.
  4. Run validate() when form is submitted
  5. Check if(wasClicked){...} in validate()

Here is a Working Example