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

236
Views
How to use blade array (appended by javascript) using separate js file?

I have a javascript function like this :

function addRow(){
$('#mainbody').append('<tr>' +
    '<td><select class="form-control" name="addmore['+i+'][name]" id="name'+i+'" required >' +
        '<option disabled="disabled" selected="selected" value="" >Select Product</option>' +
        '@foreach($produk as $pro)' +
        '<option value="{{$pro->id}}">{{$pro->nama}}</option>' +
        '@endforeach'
)}

When I use the script in the same blade (view) file, it work, but when I separate the javascript function, and included the script on header, it show the blade syntax literally like {{ $pro->id }} (not the actual number from controller, but it does append a new row with {{ $pro->name }} as the value).

So my question is, can I make a separate file for my javascript function ? Because I'm using the script in create and edit view, so I want to make my view more cleaner.

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

0

Laravel template engine can not compile javascript files but you can write your javascript code inside blade file. add your script inside blade place your data into variable json formated then loop for each on of items you want

Try this example.blade.php

<script type="text/javascript">
let produk = {!! json_encode($produk) !!};

function addRow(){
    var tr = $('<tr></tr>');
    var select = $(`<select class="form-control" name="addmore[]" required ></select>`);
    for(const pro in produk) {
        var td = $(`<option value="${ pro->id }">${ $pro->name }</option>`);
        select.append(td);
    }
    tr.append(select);
    $('#mainbody').append(tr);
}
</script>
about 4 years ago · Juan Pablo Isaza Report

0

You should assign the $produk variable js variable when this blade file has been initiated.

Below code can render $produk data into JS const datatype variable.

const produk = @json($produk)

Then you can do foreach inside the select tag

produk.forEach(element => {
    // ...use `element`...
});
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!