skip to Main Content

I am trying to implement a bus seat layout. I want seats to change it’s background color when clicked. The seats are bootstrap radio buttons with class=’seat’ and labels with class=’btn’.

I have tried to write a javascript code but I don’t seem to get .style attribute, vs code autocomplete a different attribute. Here is part of my javascript code:

document.addEventListener('DOMContentLoaded',()=>{
    document.querySelectorAll('.seat .btn').forEach(seat=>{
        seat.addEventListener('click',()=>{
            seat.computedStyleMap
        })
    })
})

the seat element:

<div class="col-3 col-sm-3 seat px-1 justify-content-end d-flex">
   <input type="radio" class="btn-check mx-1" name="seat" id="C1">
   <label class="btn" for="C1"><i class="bi bi-layout-sidebar-inset-reverse"></i>C1</label>
</div>

I have tried document.querySelector(".seat > .btn").forEach… I still get the same auto complete which is "seat.computedStyleMap". I was expecting to have "seat.style.backgroundColor = red".

2

Answers


  1. Just use CSS

    [name=seat]:checked + label {
        background-color: green !important;
        color: white !important; 
    }
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"/>
    
    <div class="col-3 col-sm-3 seat px-1 justify-content-end d-flex">
       <input type="radio" class="btn-check mx-1" name="seat" id="C1">
       <label class="btn" for="C1"><i class="bi bi-layout-sidebar-inset-reverse"></i>C1</label>
       <input type="radio" class="btn-check mx-1" name="seat" id="C2">
       <label class="btn" for="C2"><i class="bi bi-layout-sidebar-inset-reverse"></i>C2</label>
    </div>
    Login or Signup to reply.
  2. You need to select the label elements directly since they have the class btn. Also, you should use the style property to change the background color

    document.addEventListener('DOMContentLoaded', () => {
        document.querySelectorAll('.seat .btn').forEach(seat => {
            seat.addEventListener('click', () => {
                // Toggle the background color of the clicked seat
                if (seat.style.backgroundColor === 'red') {
                    seat.style.backgroundColor = ''; // Reset to default
                } else {
                    seat.style.backgroundColor = 'red'; // Change to red
                }
            });
        });
    });
    
    <div class="col-3 col-sm-3 seat px-1 justify-content-end d-flex">
        <input type="radio" class="btn-check mx-1" name="seat" id="C1">
        <label class="btn" for="C1"><i class="bi bi-layout-sidebar-inset-reverse"></i>C1</label>
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search