chaser7016 chaser7016 - 3 months ago 75
HTML Question

Show Bootstrap Modal Window based on select (DropDown) value

I have code that when an option within select drop down is chosen the proper bootstrap window appears. Yet my script is not easy to maintain. I have to add to my script with each new drop down option that is added.

What would be a more efficient way to write the following script? It would be more useful if I did not need to add to it with each new dropdown option and modal window added to the HTML.



$("#selectbox").change(function () {
if ($(this).val() == "#myModal") {
$('#myModal').modal('show');
}
if ($(this).val() == "#myModal2") {
$('#myModal2').modal('show');
}
if ($(this).val() == "#myModal3") {
$('#myModal3').modal('show');
}
});

<select class="form-control" id="selectbox">
<option value="#">
Find: App Support
</option>

<option value="#myModal">
Apple Pear Company
</option>

<option value="#myModal2">
Cold Brewing Company
</option>

<option value="#myModal3">
Jokers Wild Inc.
</option>
</select>


<div id="myModal1" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Apple Pear Company</h4>
</div>
<div class="modal-body info">
<p>Lorem lipsum
</p>
</div>
<div class="modal-footer addHEIGHT">
</div>
</div>
</div>
</div>

<div id="myModal2" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Cold Brewing Company</h4>
</div>
<div class="modal-body info">
<p>Lorem lipsum</p>
</div>
<div class="modal-footer"></div>
</div>
</div>
</div>

<div id="myModal3" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Jokers Wild Inc.</h4>
</div>
<div class="modal-body info">
<p>Lorem Lipsum</p>
</div>
<div class="modal-footer"></div>
</div>
</div>
</div>




Answer

If the values of your select options is the relevant selector (#modalId) of the modal, you can use:

$("#selectbox").change(function () {
    $( $(this).val() ).modal('show');
})
Comments