0

I can't figure out why 'onClick' function trigged twice.

My html code:

  <div class="form-actions right1">
        <button type="button" id="btnCancel" class="btn default">
            Cancel
        </button>
        <button type="submit" id="btnSubmit" class="btn blue">
            Submit
        </button>
    </div>

Script is here:

 $("#btnSubmit").on("click",function () {
            debugger;
            alert("Click");
            CreateOfficeTypeManager.SaveOfficeType();

        });
amith murakonda
  • 278
  • 2
  • 15
t_rex
  • 23
  • 1
  • 10
  • 1
    Possible the script being referenced more than once. Check @ https://stackoverflow.com/questions/3070400/jquery-button-click-event-is-triggered-twice – Thirueswaran Rajagopalan Mar 12 '18 at 09:11
  • 1
    Perhaps it is not. If it is in a form and you do not want to submit the form, you need to do this: `$("#btnSubmit").on("click",function (e) { e.preventDefault();` which is better done on the form submit event – mplungjan Mar 12 '18 at 09:13
  • This code only triggers once on my system. I think @ThirueswaranRajagopalan is right. You probably have it referenced 2 times – Nicolo Lüscher Mar 12 '18 at 09:14
  • Maybe by inspecting the `$event` passed into the callback, you can get more info of what is happening. **Debugger is your friend ..** – Thirueswaran Rajagopalan Mar 12 '18 at 09:22

2 Answers2

0

You might be binding the "click" even twice.

Put a breakpoint in your $("#btnSubmit")... instruction and see if it goes there twice.

Otherwise, try unbinding as shown here button onclick function firing twice

Finally, if you're in a complex environment, there might be other code handling the clicks for you. Try preventDefault as suggested in the comments of your question.

jeancallisti
  • 1,046
  • 1
  • 11
  • 21
0

It works fine.

 $("#btnSubmit").on("click",function () {
            debugger;
            alert("Click");

        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div class="form-actions right1">
        <button type="button" id="btnCancel" class="btn default">
            Cancel
        </button>
        <button type="submit" id="btnSubmit" class="btn blue">
            Submit
        </button>
    </div>
Ismail Rubad
  • 1,458
  • 2
  • 13
  • 27