4

I used Bootstrap modal dialog with OK/Cancel button. I expect some work to be done after OK is clicked and then close the modal dialog. So I used JS to handle OK click.

HTML:

 <div class="modal fade" id="RequestModal" tabindex="-1"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="RequestModalLabel">Confirm to submit below request?</h5> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button> <button type="button" class="btn btn-primary" id="btn_close" onclick="f_test()">OK</button> </div> </div> </div> </div> 

JS

function f_test () { var myModal = new bootstrap.Modal(document.getElementById('RequestModal')); myModal.hide(); } 

The hide function doesn't work. I searched the stackoverflow and others but didn't get good answer.

3
  • Please tag your Bootstrap version. Commented Jan 3, 2022 at 15:04
  • Please take the tour. If you have a solution you need to post it as an answer and accept it. Commented Jan 3, 2022 at 15:06
  • Based on the code above, I am guessing you are using bootstrap 5. Am I correct? And, are you seeing any error in the browser console? Commented Jan 4, 2022 at 7:53

1 Answer 1

3

You are very close. Create the object of the modal dialog first and then use it to hide on the f_test() method as shown below,

 var myModal = new bootstrap.Modal(document.getElementById('RequestModal')); myModal.show(); function f_test () { myModal.hide(); } 

JSFiddle: https://jsfiddle.net/78n9k65L/

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

1 Comment

Yes. It must be declared in 'global' scope', and not in 'function' scope. The function declaration will create new instance. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.