mercredi 6 avril 2016

JQuery / Javascript: How to replace the text in a Select Drop Down

I have 2 select drop downs on my page. When you select a category from the first drop down, an ajax call is made to fetch the products within that category and display them in a second neighbouring drop down. It all works great, except for one small detail. When I select a new category, I want the products to over write the description within the second drop down. At the moment I am using the append method and it, obviously appends them. I have tried .html and .text methods and they don't display the text.

The first drop down values are delivered from the DB using a Laravel call. It's hopefully obvious what is going on:

    {!! Form::select('categories[]',$categories,null,['class'=>'input-sm categories']) !!}

The second drop down is generated through JQuery

 $(".categories").on('change', function () {

    var value = parseFloat($(this).val());
    var $cat_products = $(".cat_products");

    $.ajax({                                                                        
        type: 'GET',
        dataType:"json",
        url: 'category_prices/' + value,
        success: function (categories) {
         $.each(categories,function(i, product){
         $cat_products.append('<option>' +product.product_name+'</option>' ) 

            });

        }
    });

});

HTML for the second drop down:

<div class="form-group row">
        <div class="col-sm-3  col-md-3"></div>
        <div class="col-sm-2  col-md-2" >
            <select class="cat_products">

            </select>
        </div>
    </div>



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire