Search code examples
javascriptjquerypreventdefault

Execute code prior to submission of modal form


I have a very simple modal form that ultimately will be used to insert data into a SQL database. As I am new to this I am just trying to confirm that control is passing correctly, however the below code does not seem to be working.

Here is my HTML code:

<div class="modal" id="new-role-modal">
        <div class="modal-dialog modal-sm">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">New User Role</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                </div> 
                <div>
                    <form method="post" id="new-role">
                        <input type="text" class="form-control" id="role-title" placeholder="Role Title" name="role-title">
                        <div class="modal-actions">
                            <div>
                                <button type="submit" class="btn-link modal-action" id="add-role" data-dismiss="modal" value="add-role"><strong>Continue</strong></button>
                                <button type="button" class="btn-link modal-action" data-dismiss="modal">Cancel</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
  </div>

My jquery code is:

$("#new-role").submit(function(e){
      e.preventDefault(e);
      alert('submit intercepted');
    });

Once I can get the alert displaying I will ultimately replace this with validation and the relevant code to add the data, but right now I can't even get the alert to display. Where have I gone wrong?


Solution

  • Change

    <button type="submit" class="btn-link modal-action" id="add-role" data-dismiss="modal" value="add-role"><strong>Continue</strong></button>
    

    to

    <button type="submit" class="btn-link modal-action" id="add-role" value="add-role"><strong>Continue</strong></button>
    

    Your script will work.

    Problem: Your submit button has attribute data-dismiss="modal" that make the modal close without run your script.