create own script function for each @foreach

Viewed 42

I want to style automatic generated table rows by clicking on a button.

At the moment my code looks like this:

@foreach($tours as $tour)
    <tr id="{{$tour->id}}">
        <td> {{$tour->tournr}} </td>
    
    <!-- ... -->

    <button onclick="myFunction()">Click me</button>
    
    <!-- ... -->

<script>
    function myFunction() {
      document.getElementById("{{$tour->id}}").style.color = "red";
    }
</script>

I cut little bit out like closing tags etc.

the button in general works, but the problem is, that always just the last row gets styled.

How can I relate the button to this special row.

I thank you in advance, kirschNN

1 Answers

Well the easier way is probably:

  1. take out the script from the foreach, otherwise you will end up with 2384728734 scripts
  2. to pass $tour->id in the onclick
<script>
function myFunction(id) {
  document.getElementById(id).style.color = "red";
}
</script>
@foreach($tours as $tour)

 <tr id="{{$tour->id}}">
    <td> {{$tour->tournr}} </td>
       <button onclick="myFunction('{{$tour->id}}')">Click me</button>

Surely there are cleaner an more maintainable way to do this, but this works without a lot of changes

Related