1

I have a Bootstrap modal that is working correctly, being triggered by a button:

<button type="button" class="btn btn-info mm" data-toggle="modal" data-target="#mm_modal" data-req="foo">

This modal works with some data from a form. I would like to display an alert and not display the modal at all, if the form data fails validation. How do I do this?

I have tried adding a function:

$('button.mm').click( function(ev)
{
    var req = $(ev.currentTarget).data('req');
    if ( req === 'foo' )
    {
        alert('Foo not supported'); 
        throw new Error('Foo not supported');
    }
}

The alert displays correctly but the throw does not seem to abort execution; the Bootstrap modal goes on to be displayed anyway.

M.M
  • 138,810
  • 21
  • 208
  • 365
  • Hmm interesting way to do that, have you tried `ev.preventDefault()` ? – Fadi Obaji Jun 07 '15 at 23:56
  • @FadiObaji Didn't work -- however doing `ev.preventDefault()` inside the `$('#mm_modal').on('show.bs.modal', function(ev) {` function did work! So I'll move my logic into there. I originally wanted to have it in there but couldn't see how to prevent the modal there either, so I figured having the logic in the click handler would make things easier... apparently not. if you post that as an answer I'll accept – M.M Jun 08 '15 at 00:06
  • ok, give me few minutes to write it :) – Fadi Obaji Jun 08 '15 at 00:08
  • I found the solution, don't change anything, i'll write the answer now ;) – Fadi Obaji Jun 08 '15 at 00:10

1 Answers1

1

The Solution (Tested and working):

Use ev.stopPropagation(); instead of the throw new Error('Foo not supported'); and the modal won't show.

NOTE using ev.preventDefault(); won't stop the modal from appearing.

The difference between stopPropagation and preventDefault: here

Hope that helps.

Community
  • 1
  • 1
Fadi Obaji
  • 1,454
  • 4
  • 27
  • 57