0

js functions in the script provided at the end of the blade should show/hide div with specific id according to the sent one in the parameter but looks like js functions don't receive php parameters from blade as the div blades are given different ids as intended but they can't be accessed from the js functions. My question is how to use functions on specific div (notice that div are created by a foreach loop with different ids)

@foreach($postsList as $post)
<div id="post_div_{{$id}}" style="font-weight:bold" class="p-6 bg-white border-b border-gray-200">

    @php
    $id=$post->id;
    @endphp

    <strong>{{$post->title}}</strong>
    <a>Added: {{$post->created_at}}</a>

    <form method="POST" action="/posts/delete/{{$post->id}}">
        <button id="DeleteButton" onclick="deletePost($id)" type="button">Delete</button>
    </form>

    <button onclick="editPost($id)" type="button">Edit</button>
    <div id="all_div_{{$id}}" class="p-6 bg-white border-b border-gray-200" style="display: none;">@include('editPost', ['post'=>$post])</div>

    <script type="text/javascript">
        function deletePost($id) {
            document.getElementById('post_div_' + {
                $id
            }).style.display = "none";
        }

        function editPost($id) {
            document.getElementById('all_div_' + {
                $id
            }).style.display = "block";
        }
    </script>
</div>
@endforeach
  • What have you tried to resolve the problem? Where are you stuck? Shouldn't you use `{{` for variables instead of a single `{`? – Nico Haase Sep 29 '21 at 09:01
  • 2
    You've to rethink the logic. Including your JavaScript in the loop doesn't do what you think it might do, after parsing, the JS script ends up to a single function (the last one defined in the loop). I'd suggest you to drop the ids (unless you need those at server-side), and base the logic on event delegation and robust DOM structure. – Teemu Sep 29 '21 at 09:05
  • @Teemu I know that including the script in the loop will only generate a single fn, I can move it after the end of the loop no problem.My question is that I want to send a specific id of the div the button is placed in. – Youssef George Sep 29 '21 at 09:16
  • 2
    Again: drop the ids, the task will become overly complex and the results are unreliable when using ids. See https://stackoverflow.com/q/1687296/1169519 There are tens of methods how you can get an element from the DOM without id. – Teemu Sep 29 '21 at 09:33
  • 1
    I made [a fiddle](https://jsfiddle.net/nxud9ocf/) for you. It's loosely related to your code, and it shows how to use event delegation and DOM structure to handle a bulk of elements with pure JS (no server-side code needed) without ids. The code works with any amount of `.all-posts` divs, and with any amount of `.post-divs` in the markup, without need to make any changes to the JS, also when `.post-div`s are dynamically added or deleted. – Teemu Sep 30 '21 at 06:14

0 Answers0