2

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 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

i have an additional question. When i reload the site the colors are gone, is there a way to avoid this?
@kirschNN there is no "easy" solution... maybe you can have a look at "local storage", and with a script updating the color when the page loads...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.