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.
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>
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`...
});