Search code examples
javascripthtmlbootstrap-modalbootstrap-5

How do I close a bootstrap (5.2) Modal from Javascript?


For a school project's sake, I created a modal using bootstrap in html, inside of it there is a prompt that I must check from javascript, how do I close the Modal from javascript, so that in case the prompt is valid I can just save the changes and if it isn't I throw an exception? small note (Please without jQuery, I've seen a similar thread that had as a reply using this library, it's forbidden for the assignment)

this is my html code :

<div class="modal fade" id="bidModal" tabindex="-1" aria-labelledby="bidModal" aria-hidden="true">
        <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="bidModalLabel">Bid amount</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p class="text" id="prompted">How much do you want to bet?</p>
                <div class="input-group mb-2">
                    <input id="bAmount" type="text" class="form-control text" aria-label="Amount of bet">
                    <span class="input-group-text">€</span>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Cancel bid</button>
                <button type="button" onClick="bid()" class="btn btn-success">Save bid</button>
            </div>
        </div>
        </div>
    </div>

this is my javascript code :

function bid(){
    let valueOfBid = document.getElementById("bAmount").value;
    if(isNaN(valueOfBid)){
        //Cancel the prompt
    }

    players[realPlayer].bet=valueOfBid;
    changeButtonState(false);
    theTimer();
}


Solution

  • Please try like this. I suggest that you change isNaN(valueOfBid) to valueOfBid == "" before you add my code on your codebase.

    function bid(){
        let valueOfBid = document.getElementById("bAmount").value;
        if(valueOfBid == ""){
          alert(1)
            //Cancel the prompt
          var myModalEl = document.getElementById('bidModal');
    var modal = bootstrap.Modal.getInstance(myModalEl)
    modal.hide();
        }
    
        // players[realPlayer].bet=valueOfBid;
        // changeButtonState(false);
    }