search

Home  >  Q&A  >  body text

How to close Bootstrap (5.2) modal using Javascript?

For the sake of a school project I have created a modal using bootstrap in html in which there is a prompt that I have to check from javascript, how can I close the modal from javascript so that if the prompt is valid I can just save Change, if not, will I throw an exception? Small note (please don't use jQuery, I've seen a similar thread that used this library as a reply disallowing allocation)

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();
}

P粉369196603P粉369196603309 days ago389

reply all(2)I'll reply

  • P粉733166744

    P粉7331667442024-02-22 13:42:45

    You can add this to the element where the modal should be turned off...

    data-bs-dismiss="modal"

    The following patterns generate a list of links based on search terms and user matches.

    When they click on one of the router links, it will turn off the modal because of that line

    {{ user }}
    

    The above code is generated in a modal -> here is the whole thing

    reply
    0
  • P粉012875927

    P粉0128759272024-02-22 09:54:25

    Please try this. I suggest you change isNaN(valueOfBid) to valueOfBid == "" before adding my code to the 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);
    }

    reply
    0
  • Cancelreply