Change the background color of input text based on conditional value [on hold]

问题: I am trying to create an input text field, and when values like 1, 2, 3 are typed in the text field the background color of the text field will change to Red, Yellow, and G...

问题:

I am trying to create an input text field, and when values like 1, 2, 3 are typed in the text field the background color of the text field will change to Red, Yellow, and Green, respectively. I have find some clue here but unable to get my desired output (Conditional format). Not that great in js, so any help will be highly appreciated


回答1:

Method-01:
Using switch:

HTML:

<input type="number" id="color" />

JS:

function changeColor(e){
    var color;

    switch(e.target.value){
        case 1:
            color = "red";
            break;
        case 2:
            color = "yellow";
            break;
        case 3:
            color = "green";
            break;
        default:
            color = "white";
    }
    e.target.style.backgroundColor = color;
}

document.getElementById("color").addEventListener("input", changeColor);

Method-02:
Using if else:

HTML:

<input type="number" id="color" />    

JS:

function changeColor(e){
    var value = e.target.value;
    var color;

    if(value == 1){
        color = "red";
    }
    else if(value == 2){
        color = "yellow";
    }
    else if(value == 3){
         color = "green";
    }
    else {
         color = "white";
    }

    e.target.style.backgroundColor = color;
}

document.getElementById("color").addEventListener("input", changeColor);

回答2:

There are many ways but this is one way how you could do it:

const colors = document.querySelectorAll('.colors');

for (let color of colors) {
  color.addEventListener('keyup', () => {
    if (this.event.target.value == 1) {
      this.event.target.style.backgroundColor = 'red';
    }
    else if (this.event.target.value == 2) {
      this.event.target.style.backgroundColor = 'yellow';
    }
    else if (this.event.target.value == 3) {
      this.event.target.style.backgroundColor = 'green';
    }
    else {
      this.event.target.style.backgroundColor = 'inherit';
    }
  })
}
<input type="text" class="colors">
<input type="text" class="colors">
<input type="text" class="colors">

  • 发表于 2019-03-30 03:15
  • 阅读 ( 193 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除