Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

455
Views
How can use foreach loop in js file?
$(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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!