Ad

Call Javascript Library After AJAX Success

- 1 answer

I have a main page that uses an AJAX call to expose content from a second page depending on user selection. One of the elements that is generated by the second page is a dropdown list. My dropdown lists are formatted using a Javascript library.

The issue I'm having is that, if I put the dropdown element on the main page, it renders with no issue at all. However, if it's rendered by the second page (via AJAX), the dropdown doesn't render. I feel like I need to somehow call the library again upon success but I'm honestly not sure.

Here's the AJAX code from my main page:

<script type="text/javascript">
    jQuery('input[name="location"]').click(function(){
        var data = {location : jQuery(this).val(), department : $('input[name="department"]:checked').val(), userID : 12345};
        jQuery.ajax({
            url: "/new-custom.php",
            type:'POST',
            data: data,
            dataType: 'html',
            async: 'true',
            success: function(result){
                jQuery('#div-custom').html(result).show(); 
            }
        });        
    });
</script>

Here's the form element rendered on new-custom.php:

<div class="form-group">
    <label class="control-label" for="field_20">Room Type</label>
    <select class="form-control selectpicker" id="field_20" name="field_20">
        <option value="0" selected>Select an option</option>
        <option value="Double">Double</option>
        <option value="Queen">Queen</option>
        <option value="Standard">Standard</option>
        <option value="King">King</option>
    </select>
</div>

And here's the Javascript library that gets included on my main page:

<script src="/vendors/bower_components/bootstrap-select/dist/js/bootstrap-select.js"></script>

Do I need to somehow execute the bootstrap-select.js library on the AJAX success function?

Many thanks in advance for any help!

Ad

Answer

You need to initialize the plugin on the newly added elements after you add them.

Change your code to :

        success: function(result){
            jQuery('#div-custom').html(result).show().find('.selectpicker').selectpicker(); // initialize new elements
        }
Ad
source: stackoverflow.com
Ad