0

I'm struggling with a problem for several days despite searching all the web out ! Here is my structure, i'm using :

  • An HTML form, which has no submit button but an input type='button' instead. This button launches a bootstrap modal (basically, in a form validation purpose)
  • The modal has 2 buttons, 1 submitting the form, 1 cancelling the process.

All I want is execute a jQuery function when the submitting button is clicked but... when using :

  • onclick='alert('test') : it works perfectly fine
  • $('#id').on('click', alert('test')) : the alert appears when the page is loaded and... twice ! (why twice ???)
  • $('#id').click(alert('test')); : same problem as previous

For several reasons, i really want to use the 2nd method. So can anyone help me to understand what's happening here, and how I fix this problem please ?

Here is my form :

<form action='' novalidate>
    <input type="button" name="btn" value="send" data-toggle="modal" data-target="#modal_AR_confirmSubmit"/>
</form>

And my modal :

<div class="modal fade" id="modal_AR_confirmSubmit" role="dialog">
    <div class="modal-dialog">
      
      <div class="modal-content">
        <div class="modal-header bg-dark text-white">
          <h4 class="modal-title">Title</h4>
        </div>
        <div class="modal-body">
          <p id='modal_AR_confirmSubmit-body'>Content</p>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-primary" data-dismiss="modal" id='id'>Valider</button>
            <button type="button" class="btn btn-danger" data-dismiss="modal">Annuler</button>
        </div>
      </div>
       
    </div>
</div>

Thanks a lot !

1 Answer 1

1

$('#id').on('click', alert('test')) is not right syntax, event handlers excepts functions:

$('#id').on('click', function(){ alert('test')}) 

jquery on

3
  • First of all, thank you very much for your answer which... works ! (I was convinced I had tried this but... anyway !) I can't help asking myself why you can't mention an existing function right away (instead of re-writing "function(){}") Commented Apr 17, 2021 at 18:47
  • @John-Deluxe Np, please consider marking this anwser on ✔︎ button so it marks the question as solved for others. Cheers.
    – ikiK
    Commented Apr 17, 2021 at 18:51
  • It's done ! (At least, I think so. if I did wrong, don't hesitate to remind me !) Commented Apr 18, 2021 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.