Skip to content
Advertisement

How to change background of div using button

I have code:

<?php
$link = mysqli_connect("localhost", "name", "password", "database");
$query = mysqli_query($link, "SELECT name, city, subject FROM user");

while($result = mysqli_fetch_assoc($query)) {
    $output = '<div class="block" style="background: grey">
          <form method="post">
          <p>Name: '.$result['name'].'</p>
          <p>Subject: '.$result['subject'].'</p>
          <p>City: '.$result['city'].'</p>
          <input type="button" name="grey" value="grey">
          <input type="button" name="red" value="red">
          </form>
          </div>';

    echo $output;
}
?>

How can I change background color of <div class="block"> using buttons <input type="button" name="grey" value="grey"> and <input type="button" name="red" value="red">? I tried to do it, but nothing helps. Who knows? P.S.: it doesn’t matter, what to use (PHP or JS).

Advertisement

Answer

for do that you can use javascript. I suggest to change the class of the div when button is clicked and add the good rules in css, or just change style property of the element. But css is here for taht and it’s more clean to do that with classes and css. You have also to add an id to the button like #red or #blue Exemple with classes :

const div = document.querySelector('.block');
const btnRed = document.querySelector('#red');
const btnBlue = document.querySelector('#blue');
    
// Get the click on the button
btnRed.addEventListener('click', () => {
    // Change classes
    div.classList.add('red');
    div.classList.remove('blue');
    // If you don't want to use classes, change the background property
    div.style.backgroundColor = "red";
})

And it’s the contrary for the blue button

If you have several div,I think you can do that :

const div = document.querySelectorAll('.block');
const btnRed = document.querySelector('#red');
const btnBlue = document.querySelector('#blue');
    
// Get the click on the button
btnRed.addEventListener('click', () => {
div.forEach(item => {
    // Change classes
    item.classList.add('red');
    item.classList.remove('blue');
    // If you don't want to use classes, change the background property
    item.style.backgroundColor = "red";
})
})
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement