Camille BOUQUET
Camille BOUQUET

Reputation: 423

Change the color of a button while clicking on it flask js html

I have a button ON/OFF, when I click on it to put it ON I want the button to become green and when I click on it to put it OFF I want the button to become red.

I am using Flask with Python HTML Javascript

Here is my line for the button in html:

<input onclick="changeColor()" type="submit" name="drive_state" id="onoffbutton" value={{drive_state}}>

The value {{drive_state}} is coded in the python file. The values of this button are either "On" or "Off".

So, I created this javascript file:

function changeColor() {
    if (document.getElementById("onoffbutton").value == 'On') {
        document.getElementById("onoffbutton").style.backgroundColor = '#3DCE65';
    }else {
        document.getElementById("onoffbutton").style.backgroundColor = '#CF1823';
    }    
}

But whenever I am clicking on this ON/OFF button, I receive the following error: The browser (or proxy) sent a request that this server could not understand.

Upvotes: 1

Views: 1361

Answers (1)

Weyers de Lange
Weyers de Lange

Reputation: 290

Css button and create event inside button

.mystyle {
 background-color: red;
  border-radius: 8px;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
}
button {
  background-color: #4CAF50;
  border-radius: 8px;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>

</style>
</head>
<body>



<button id="button" onclick="myFunction()">ON/OFF</button>



<script>
function myFunction() {
   var element = document.getElementById("button");
   element.classList.toggle("mystyle");
}
</script>

</body>
</html>

Upvotes: 2

Related Questions