Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

454
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda