1

I want to check if the background colour of an input field is e.g. green when the input is changed. I have tried most things, but nothing seems to work. Why does this not work? I think it is the condition in the if statement that does not work, as I have tried both alert and value inside the if statement.
The following is a minimal reproducible example:

function myFunction(chosenID) {
  if (document.getElementById(chosenID).style.backgroundColor == "#99ff99") {
    document.getElementById(chosenID).value = "You tried to change a form with a background colour already"
  }
}
<html>

<body>
  <input type="text" id="a" value="Non-coloured input field" onChange="myFunction('a')">
  <input type="text" id="b" value="Coloured input field" onChange="myFunction('b')" style="background-color: #99ff99">
</body>

</html>

Edit

I do not think that this is a duplicate. My question is about not getting the desired result from a function, not about conversion between RGB and HEX. Therefore, this should be reopened.
norway-yv
  • 222
  • 2
  • 12
  • 5
    If you log out the value of `document.getElementById(chosenID).style.backgroundColor` you'll see the problem, the browser is returning the colour in RGB rather than hex. – DBS Apr 05 '22 at 10:51
  • 1
    This is easy if you know how to debug. See [Debug JavaScript - Chrome Developers](https://developer.chrome.com/docs/devtools/javascript/) – Julian Apr 05 '22 at 10:51
  • Also, you should probably use `getComputedStyle()` to encompass all CSS and inline styling. - `getComputedStyle(document.getElementById(chosenID)).backgroundColor` – phuzi Apr 05 '22 at 10:53
  • try this `element.style.getPropertyValue('background-color')` – A.Anvarbekov Apr 05 '22 at 11:03
  • myInputTypeObj = document.getElementById("choosenID"); const myInputTypeObjBgColor = window.getComputedStyle(myInputTypeObj).backgroundColor; alert(myInputTypeObjBgColor); if(myInputTypeObjBgColor == "rgb(0, 128, 0)") { //your condition } – ZKS Apr 05 '22 at 11:06
  • @A.Anvarbekov That did unfortunately not work. – norway-yv Apr 05 '22 at 11:50

0 Answers0