Search code examples
javascriptjquerybootstrap-modal

Execute JavaScript in a modal window


I have the following JS code:

<script type="text/javascript">  
    $(document).ready(function () {  
        var items = "<option value='0'>Select</option>";  
        $('#DistrictID').html(items);  
    });  
</script>  

This populate a dropdownlist with the value Select, the thing is, this dropdownlist appears in a form that it's called once the user clicks a button and then a modal windows opens, with the form in it.

But since it is mark as

$(document).ready  

This JS won't execute with the modal, since the document is already 'ready'. How can I achieve this?

Thanks in advance!

Regards,


Solution

  • You can easily achieve this using bootstrap modal events. You can use following code snippet to achieve your objective:

    $(document).ready(function () { 
         $('#myModal').on('shown.bs.modal', function (e) {
                var items = "<option value='0'>Select</option>";  
                $('#DistrictID').html(items); 
          });
    });
    

    For reference Please check bootstrap modal events.