Saturday, March 4, 2017

Add selectpicker to dynamic input

I am using Laravel. Within my controller, I pass my view a list of questions. I then display things like so

@foreach($questions as $q)
    <div class="col-xs-12">
        <input type="" class="form-control ">
    </div>
@endforeach

Now some of these inputs have a type select, and a class which is then set to selectpicker. Now normally, to set the selectpicker I would use something like this

$(function () {
    $('.selectpicker').selectpicker();
});

But because it is being added after the DOM it does not work. I have searched online and tried suggestions like this

$('body').on('focus',".selectpicker", function(){
    if( $(this).hasClass('selectpicker') === false )  {
        $(this).selectpicker({
            liveSearch: true
        });
    }
});

However the above does not seem to work. How can I get selectpicker working on dynamically added elements?

Thanks



via kate_hudson

Advertisement