How can use foreach loop in js file?

Viewed 77
$(document).ready(function() {
        $("form").on("click", ".addRow", function(){
            var ttr =   '<div class="row add tr">'+
                           '<div class="col">'+
                                '<select class="form-control single purchaseCat" name="category_id[]">'+
                                   '<option value="">Select Category</option>'+
                                   '@foreach($categories as $category)'+
                                   '<option value="{{$category->id}}">{{$category->category_name}}</option>'+
                                   '@endforeach'+
                                '</select>'+
                            '</div>'+    
                         '</div>'
            $('.invoice_table').append(ttr);
        });
    });

I'm using a dynamic dropdown. If you check the image you can understand the problem is. when i add new row this time foreach didn't work

https://i.stack.imgur.com/7ZSP5.png

1 Answers

The issues is most likely because the @foreach is a Laravel instruction which won't be executed inside a .js file.

The simple way to do what you need is to use clone() to copy an existing row and then append() that to the DOM where required

$(document).ready(function() {
  $("form").on("click", ".addRow", function() {
    let $newRow = $('div.row:first').clone();
    $newRow.find('select.purchaseCat').val(''); // reset selected option to default
    $('.invoice_table').append($newRow);
  });
});

Also, just as an aside to the question, it looks like you're using div elements to create a table, which is a little odd. Remember that it's absolutely valid and correct to use a table element for tabular data. It's only using tables for layout that should be avoided.

Related