Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

449
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda