Stefano Lista
Stefano Lista

Reputation: 45

Bootstrap v5, how to pass a variable inside a modal (without jquery)

it's my first question :-) I'm trying to pass a variable into a modal window in Bootstrap v5 possibly without use of jquery (v5 doesn't use it anymore).

I have a button:

<button class="btn btn-primary" id="sendMailButton">Send an Email</button>

This button fires a function "sendMailClicked"

document.getElementById("sendMailButton").addEventListener("click", sendMailClicked);

and this is the function

function sendMailClicked() {
   var theValue = document.getElementById('inputid').value;  
   var myModal = new bootstrap.Modal(document.getElementById('emailModal'), { backdrop: 'static' })
   myModal.show();
}

inside sendMailClicked the variable "theValue" is defined and its value is correct. I want to pass this variable inside a modal window whose content should be like this: your value is theValue

<div class="modal fade" id="emailModal" tabindex="-1" aria-labelledby="exampleModalLabel"
                aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="exampleModalLabel">Do you want to send an email?</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            Your value is <?= theValue ?>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">No</button>
                            <button type="button" class="btn btn-primary" id="yesSendMail" value="<?= theValue ?>">Ok invia</button>
                        </div>
                    </div>
                </div>
            </div>

I suppose being the modal window preloaded in HTML is the reason why theValue is undefined. Is there a way to pass theValue value to the modal window? The ideal solution would be doing it without jquery (not included in Bootstrap v5).

Upvotes: 3

Views: 3612

Answers (1)

Alex Boutin
Alex Boutin

Reputation: 187

You can use multiple methods but I'm guessing the best would be to target the child in your modal inside you sendMailClicked function, and then set the inner html to whatever you want.

function sendMailClicked() {
   var theValue = document.getElementById('inputid').value;  
   var modalContainer = document.getElementById('emailModal')
   var myModal = new bootstrap.Modal(modalContainer, { backdrop: 'static' })
   
   modalContainer.querySelector(".modal-body").innerHTML = "Your value is: " + theValue;
   
   myModal.show();
}

Upvotes: 2

Related Questions