1

I'm using Bootstrap 3 to create modal form. Before user click button to open the modal, there is a field validation.

If it is valid then modal is shown, otherwise prevent the modal from being shown.

The problem is on the second chance, user click the button and the modal won't display. How to solve this problem?

Code to show modal and prevent modal from being shown: jsfiddle

$("#btnLookupClient").click(function (e) { if ($("select[name='OfficeID'] option:selected").index() <= 0) { alert("Please select office"); $("#OfficeID").focus(); $("#clientModal").on("show.bs.modal", function (e) { return e.preventDefault() // stops modal from being shown }); } else { var url = '@Url.Content("~/Client/Search?officeID=")' + $("#OfficeID").val(); $.get(url) .done(function (data) { $("#lookup-client-container").html(data); $("#clientModal").modal(show = true, backdrop = true); }); } }); 
2
  • can you show your html and fiddle ? Commented Sep 24, 2014 at 10:08
  • @Jake745 http://jsfiddle.net/rsxb8tku/ Commented Sep 24, 2014 at 10:20

2 Answers 2

1

Use one() instead of on().

$("#clientModal").one("show.bs.modal", function (e) { return e.preventDefault() // stops modal from being shown }); 

See here : http://jsfiddle.net/akcbj4n5/1/
Also reference : Difference between jQuery.one() and jQuery.on()

Sign up to request clarification or add additional context in comments.

Comments

1

when the alert gets shown you are binding the preventDefault to the event that shows the modal so it will never be shown again, even when the validation passes.

I'd suggest using the .one() function instead of .on() http://api.jquery.com/one/

Also you're modal will fire without having to call it in javascript because you set the toggle to modal and the target to the modal id.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.