Home > Blockchain >  How to change background color of an input field with conditionals in JavaScript
How to change background color of an input field with conditionals in JavaScript

Time:01-21

I tried to change the background color of the input field with an if statement. I dont know why it isnt working. What can I do to get it working?

function increment() {

  var textbox = document.
  getElementById("inc");
  textbox.value  ;
}

var inputfield = document.getElementById("inc")


// trying to change bg color of inputfield if number higher or lower -- doesnt work yet 
if (inputfield.value > 3) {
  inputfield.style.backgroundColor = "#AA0000";
}
  <div class = wrapper>

    <button onclick="increment()">Click to   1!</button>

    <input  id="inc" type="text" value="0" />

  </div>

 

CodePudding user response:

You will have to add addEventListener with input event change for your input field in order to track/check for current value (each time the value changed).

Simplified example:

const myInput = document.getElementById('my-input');

myInput.addEventListener('input', function(event) {

  console.log(event.target.value);
  if ( event.target.value >= 3) {
    myInput.classList.add('error');
  } else {
    myInput.classList.remove('error');
  }
});
#my-input {
  border: 1px solid black;
}

.error {
  background: #AA0000;
  color: white;
}
<input id="my-input" type="number" />

CodePudding user response:

Check this out.

const inputfield = document.getElementById("change_color_example")

inputfield.addEventListener("keyup", function() {
  if (this.value > 3) {
    this.classList.add("active-math")
  } else {
    this.classList.remove("active-math")
  }

  if (this.value.length > 3) {
    this.classList.add("active-length")
  } else {
    this.classList.remove("active-length")
  }
})
.example-input {
  color: #333333;
  background-color: #ffffff;
  border: 1px solid #000000;
  transition: all 300ms linear;
}

.example-input.active-math {
  color: #f8f8f8;
  background-color: #AA0000;
}

.example-input.active-length {
  color: blue;
  background-color: bisque;
}
<input type="text" id="change_color_example"  />

CodePudding user response:

We can start of by grabbing the input element from the DOM.

const input = document.querySelector('input');

Once we have the element to work with we can, we can add an event listener (blur) so whenever a user moves out of the box the action in the code will be performed. JS:

const input = document.getElementById("input");
input.addEventListener("blur", () => {
  if (input.value.length > 3) {
    input.style.backgroundColor = "red";
  }
});

HTML:

<input type="text" id="input" />
  • Related