weixin_33725515 2017-08-02 01:36 采纳率: 0%
浏览 42

Laravel追加不起作用

I am new to ajax and i am currently developing a laravel project. i have a problem with the append code because it does not show anything on my html tag. here is my javascript code:

$(document).ready(function() {
    $(document).on('change', '#product_category', function() {
        var cat_id = $(this).val();
        $.ajax({
            type: 'get',
            url: '{!! URL::to('findProductName ') !!}',
            data: {
                'id': cat_id
            },
            success: function(data) {
                console.log('success');
                console.log(data);
                var op = " ";
                op += '<option value="0" selected disabled>Choose Product</option>';
                for (var i = 0; i < data.length; i++) {
                    op += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
                }
                var div = $(this).parent();
                div.find('.choice').html(" ");
                div.find('.choice').append(op);
            },
            error: function() {

            }
        });
    });
});

HTML:

<tr id="orig_field">
    <td>
        <select name="" class="form-control" id="product_category">
            <option value="0" disabled="true" selected="true">Category...</option>
            @foreach($category as $cat)
                <option value="{{ $cat->id }}">{{ $cat->name }}</option>
            @endforeach
        </select>
    </td>
    <td>
        <select name="" class="form-control" id="prod_name">
            <option value="0" disabled="true" selected="true">Choose</option>
            <div class="choice"></div>
        </select>
    </td>
    <td id="getRequest"></td>
    <td>
        <input type="number" class="form-control" name="sale_qty[]" min="0">
    </td>
    <td></td>
</tr>
<tr id="copy_field"></tr>                

i have posted this a while ago but i'm new to stack-overflow and didn't provide the whole details. help is much appreciated thanks

  • 写回答

1条回答 默认 最新

  • lrony* 2017-08-02 01:53
    关注

    You cannot have a div inside a select. But you can just append the options to the select:

    // this array emulates your response from the ajax call
    var data = [
      { "id": 1, "name": "Product 1" },
      { "id": 2, "name": "Product 2" },
      { "id": 3, "name": "Product 3" },
      { "id": 4, "name": "Product 4" },
      { "id": 5, "name": "Product 5" },
    ],
        products = $("select[name=prod_name]");
    
    jQuery.each(data, function( index, value ) {
      products.append('<option value="' + value.id + '">' + value.name + '</option>');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <form action="#" method="post">
      <select name="prod_name">
        <option value="0" disabled="true" selected="true">Choose</option>
      </select>
    </form>

    </div>
    
    评论

报告相同问题?