I’m using laravel 8 and I am trying to create a table for multiple inserts and in that table there is a dropdown that has already fetched data from the database. I have tried to enter code like this and the dropdown doesn’t work. Here is the javascript code:
<script>
$(document).ready(function () {
let baris = 1
$(document).on('click', '#tambah', function () {
baris = baris + 1
var html = "<tr id='baris'" +baris+ ">"
html +="<td>"+baris+"</td>"
html +="<td contenteditable='true' class='id_barang'>"
html += "<select class='form-control' class='id_barang' id='id_barang' name='id_barang' required>"
html += "<option value='' hidden>-- Pilih Barang --</option>"
html += "@foreach ($benang as $data)"
html += "<option value='{{ $data->id_barang }}'>{{ $data->id_barang }}</option>"
html += "@endforeach"
html += "</select>"
html += "</td>"
html +="<td contenteditable='true' class='pekerjaan'></td>"
html +="<td contenteditable='true' class='alamat'></td>"
html +="<td> <button class='btn-sm btn-danger' data-row='baris' id='hapus'>-</button> </td>"
html += "</tr>"
$('#tabel1').append(html)
});
});
</script>
The code that I entered is the code that I entered in the view and it can work but when using javascript the dropdown cannot work
2
Answers
I’m not quite familiar with Blade, but I think you are mixing your JS code with your blade code, you are appending
"@foreach ($benang as $data)"
to a string, but most likely it is interpreted as blade code and results in Javascript with syntax errors.Your dropdown will also only have two options, always. Are you sure you iterate at the right position?
This is my attempt at making something that works.
I believe you are trying to loop the
$benang
data in your Javascript code after#tambah
element was click. However, it won’t work as Javascript can’t compile the blade component, thus it will display on your web page as a string.There are several ways to achieve the Javascript method.
$benang
into a Javascript variable. This will only work if your Javascript is in your blade file (example: home.blade.php).The code a
home.blade.php
home.js