'how to use @foreach inside AJAX & jQuery code for insert Multiple rows Data in Laravel 8
The code it works normal when i put option in static mode, for example:
"<select name='id_post[]' id='' class='form-control'>"+
"<option value='1'>A</option>"+
"<option value='2'>B</option>"+
"<option value='3'>C</option>"+
"</select>"+
but it doesn't work when I use the foreach loop in the script so adding doesn't work
<script>
$('thead').on('click', '.addRow', function(){
var tr ="<tr>" +
"<td style='display:none;'><input type='text' name='id_article[]' value='{{ $article->id_article }}' class='form-control'></td>"+
"<td>"+
"<select name='id_post[]' id='' class='form-control'>"+
"@foreach ($posts as $post)"+
"<option value='{{ $post->id_post }}'>{{ $post->description }}</option>"+
"@endforeach"+
"</select>"+
"</td>"+
"<td><input type='text' name='price[]' class='form-control'></td>"+
"<td><a href='javascript:void(0)' class='btn btn-danger deleteRow'>-</a></td>"+
"</tr>";
$('tbody').append(tr);
});
$('tbody').on('click', '.deleteRow', function(){
$(this).parent().parent().remove();
});
</script>
Solution 1:[1]
Move the @foreach
out of the concatenation:
<script>
$('thead').on('click', '.addRow', function(){
var tr ="<tr>" +
"<td style='display:none;'><input type='text' name='id_article[]' value='{{ $article->id_article }}' class='form-control'></td>"+
"<td>"+
"<select name='id_post[]' id='' class='form-control'>";
@foreach ($posts as $post)
tr += "<option value='{{ $post->id_post }}'>{{ $post->description }}</option>"
@endforeach
tr += "</select>"+
"</td>"+
"<td><input type='text' name='price[]' class='form-control'></td>"+
"<td><a href='javascript:void(0)' class='btn btn-danger deleteRow'>-</a></td>"+
"</tr>";
$('tbody').append(tr);
});
$('tbody').on('click', '.deleteRow', function(){
$(this).parent().parent().remove();
});
</script>
This should work, haven't tested it
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | brombeer |