1
$(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.sstatic.net/7ZSP5.png

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you sir, now it's worked. I try to avoid using div in table. I just using a form from bootstrap.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.