learner
learner

Reputation: 4818

How to call another function on clicking of Modal button?

I want to use bootstrap modal in my page. At the same time, when modal trigger button is clicked, I want to do something in javascript also. It's not working.

<button type="button" class="btn btn-primary center-block" id="start_quiz" data-toggle="modal" data-target="#myModal">
    Start Quiz
</button>

The button on clicking lauches modal but unable to call:

$('#start_quiz').click(function(){
            alert("hello from javascript");  
        });

How can I achieve both results at the same time? Please help me.

Upvotes: 3

Views: 4647

Answers (1)

bgs264
bgs264

Reputation: 4642

Remove the data-toggle="modal" data-target="#myModal" attributes from the button, so that it doesn't open the modal.

Then check that the "hello from javascript" displays - it should do.

Then open the modal from javascript code instead, add this line below your alert:

$('#myModal').modal('show')

This should now make the alert, then show the modal. You can always reverse the two if you want the modal shown first.

Second option, hook into the shown method and write your javascript there:

$('#myModal').on('shown.bs.modal', function () {
  // alert here
})

Upvotes: 3

Related Questions