根据输入更改输入数字类型的CSS

时间:2015-05-22 14:30:14

标签: javascript css html5

我不确定我问的是否可能。但我无法在谷歌上找到任何解决这个问题的方法。这是我正在尝试做的...我有5个输入标签,所有这些都是数字。如果值是有效数字(最大/最小值内的数字),如果存在字母(或无效数字),我希望边框变为绿色,我希望边框变为红色。我试图在昨天自己解决这个问题,但不能。

HTML

 window.onkeyup = function(e) {
   var inputs = document.getElementsByClassName("C1");
   for (i = 0; i < inputs.length; i++) {
     inputsVal = inputs[i].value;
     if (!inputsVal || inputsVal == "" || inputsVal == " ") {
       return false
     }
   }
   document.getElementById('enterSign').style.display = "block";
   document.getElementById('spacer').style.display = "none";
   if (event.which == 13) {
     saveitem();
   }
 };
<div id='nav'>
  <label for='speed'>&nbsp;Speed
    <br />
    <input type='number' class='C1' id='speed' placeholder='1-10' max='10' min='1' />
  </label>
  <br />
  <label for='Iron'>&nbsp;Iron
    <br />
    <input type='number' class='C1' id='Iron' placeholder='1-5' max='5' min='1' />
  </label>
  <br />
  <label for='Ice'>&nbsp;Ice
    <br />
    <input type='number' class='C1' id='Ice' placeholder='1-5' max='5' min='1' />
  </label>
  <br />
  <label for='Mass'>&nbsp;Mass
    <br />
    <input type='number' class='C1' id='Mass' placeholder='1-5' max='5' min='1' />
  </label>
  <br />
  <label for='Diameter'>&nbsp;Diameter
    <br />
    <input type='number' class='C1' id='Diameter' placeholder='1-5' max='5' min='1' />
  </label>
  <br />
  <center>
    <p id='spacer'>&nbsp;</p>
    <p id='enterSign' onclick='saveitem()'>Press Enter</p>
  </center>
  <center>
    <button id='btnReset' onclick='resetPage()'>Reset</button>
  </center>
</div>

目前,除非输入所有字段,否则代码将返回false。然后会出现一个div,指示用户按Enter键。但在此之前,我希望用户在进入下一个字段之前了解哪些信息是有效的。提前感谢任何可以帮助我解决此问题的人,并帮助我了解有关如何使用JavaScript处理这些事情的更多信息。 (拜托,没有jquery或其他图书馆。)我正在尝试自学JS。

5 个答案:

答案 0 :(得分:4)

一种方法如下:

window.onkeyup = function(e) {

  // getting all the <input> elements with the class of 'C1':
  var inputs = document.querySelectorAll('.C1'),

  // variables for later use within the loop:
    current, min, max, test;

  // iterating over the <input> elements with a
  // for loop:
  for (var i = 0, len = inputs.length; i < len; i++) {

    // caching the current <input> element:
    current = inputs[i];

    // getting the value of the min and max attributes,
    // parsed as a number in base 10:
    min = parseInt(current.min, 10);
    max = parseInt(current.max, 10);

    // testing whether the current value is
    // equal to, or greater than, the min AND
    // is equal to, or less than, the max:
    isValid = current.value >= min && current.value <= max;

    // if the current value is not the default value
    // (so the user has made a change to the held value):
    if (current.value !== current.defaultValue) {

      // if the number is valid:
      if (isValid) {

        // we remove the 'invalid' class-name (if it's there):
        current.classList.remove('invalid');

        // we add the 'valid' class-name:
        current.classList.add('valid');
      } else {

        current.classList.remove('valid');
        current.classList.add('invalid');
      }
    }
  }


  document.getElementById('enterSign').style.display = "block";
  document.getElementById('spacer').style.display = "none";
  if (event.which == 13) {
    saveitem();
  }
};

window.onkeyup = function(e) {

  var inputs = document.querySelectorAll('.C1'),
    current, min, max, test;

  for (var i = 0, len = inputs.length; i < len; i++) {

    current = inputs[i];

    min = parseInt(current.min, 10);
    max = parseInt(current.max, 10);

    isValid = current.value >= min && current.value <= max;
    if (current.value !== current.defaultValue) {
      if (isValid) {
        current.classList.remove('invalid');
        current.classList.add('valid');
      } else {

        current.classList.remove('valid');
        current.classList.add('invalid');
      }
    }
  }


  document.getElementById('enterSign').style.display = "block";
  document.getElementById('spacer').style.display = "none";
  if (event.which == 13) {
    saveitem();
  }
};
.valid {
  border-color: limegreen;
}
.invalid {
  border-color: red;
}
<div id='nav'>
  <label for='speed'>&nbsp;Speed
    <br />
    <input type='number' class='C1' id='speed' placeholder='1-10' max='10' min='1' />
  </label>
  <br />
  <label for='Iron'>&nbsp;Iron
    <br />
    <input type='number' class='C1' id='Iron' placeholder='1-5' max='5' min='1' />
  </label>
  <br />
  <label for='Ice'>&nbsp;Ice
    <br />
    <input type='number' class='C1' id='Ice' placeholder='1-5' max='5' min='1' />
  </label>
  <br />
  <label for='Mass'>&nbsp;Mass
    <br />
    <input type='number' class='C1' id='Mass' placeholder='1-5' max='5' min='1' />
  </label>
  <br />
  <label for='Diameter'>&nbsp;Diameter
    <br />
    <input type='number' class='C1' id='Diameter' placeholder='1-5' max='5' min='1' />
  </label>
  <br />
  <p id='spacer'>&nbsp;</p>
  <p id='enterSign' onclick='saveitem()'>Press Enter</p>

  <button id='btnReset' onclick='resetPage()'>Reset</button>

</div>

JS Fiddle demo

上述方法为window交互keyup'监听'以提供事件处理,这意味着该事件不仅必须从{{1}传播在调用函数之前,元素一直遍历每个祖先元素,也可能会在其中一个父元素上意外调用<input>,这取决于事件传播被停止,可能会阻止函数永远被称为。

当然,您可以将事件监听器附加到event.stopPropagation()元素的更近的共同祖先,例如父<input>

<div>

var commonAncestor = document.getElementById('nav');

commonAncestor.onkeyup = function(e) {
 // ... all contents removed for brevity
};
var commonAncestor = document.getElementById('nav');

commonAncestor.onkeyup = function(e) {

  var inputs = document.querySelectorAll('.C1'),
    current, min, max, test;

  for (var i = 0, len = inputs.length; i < len; i++) {

    current = inputs[i];

    min = parseInt(current.min, 10);
    max = parseInt(current.max, 10);

    isValid = current.value >= min && current.value <= max;
    if (current.value !== current.defaultValue) {
      if (isValid) {
        current.classList.remove('invalid');
        current.classList.add('valid');
      } else {

        current.classList.remove('valid');
        current.classList.add('invalid');
      }
    }
  }


  document.getElementById('enterSign').style.display = "block";
  document.getElementById('spacer').style.display = "none";
  if (event.which == 13) {
    saveitem();
  }
};
.valid {
  border-color: limegreen;
}
.invalid {
  border-color: red;
}

JS Fiddle demo

或者您可以使用<div id='nav'> <label for='speed'>&nbsp;Speed <br /> <input type='number' class='C1' id='speed' placeholder='1-10' max='10' min='1' /> </label> <br /> <label for='Iron'>&nbsp;Iron <br /> <input type='number' class='C1' id='Iron' placeholder='1-5' max='5' min='1' /> </label> <br /> <label for='Ice'>&nbsp;Ice <br /> <input type='number' class='C1' id='Ice' placeholder='1-5' max='5' min='1' /> </label> <br /> <label for='Mass'>&nbsp;Mass <br /> <input type='number' class='C1' id='Mass' placeholder='1-5' max='5' min='1' /> </label> <br /> <label for='Diameter'>&nbsp;Diameter <br /> <input type='number' class='C1' id='Diameter' placeholder='1-5' max='5' min='1' /> </label> <br /> <p id='spacer'>&nbsp;</p> <p id='enterSign' onclick='saveitem()'>Press Enter</p> <button id='btnReset' onclick='resetPage()'>Reset</button> </div>:valid选择器在CSS中实现此功能:

:invalid

:valid {
  border-color: green;
}
:invalid {
  border-color: red;
}
:valid {
  border-color: green;
}
:invalid {
  border-color: red;
}

JS Fiddle demo

当然,范围选择器 - <div id='nav'> <label for='speed'>&nbsp;Speed <br /> <input type='number' class='C1' id='speed' placeholder='1-10' max='10' min='1' /> </label> <br /> <label for='Iron'>&nbsp;Iron <br /> <input type='number' class='C1' id='Iron' placeholder='1-5' max='5' min='1' /> </label> <br /> <label for='Ice'>&nbsp;Ice <br /> <input type='number' class='C1' id='Ice' placeholder='1-5' max='5' min='1' /> </label> <br /> <label for='Mass'>&nbsp;Mass <br /> <input type='number' class='C1' id='Mass' placeholder='1-5' max='5' min='1' /> </label> <br /> <label for='Diameter'>&nbsp;Diameter <br /> <input type='number' class='C1' id='Diameter' placeholder='1-5' max='5' min='1' /> </label> <br /> <p id='spacer'>&nbsp;</p> <p id='enterSign' onclick='saveitem()'>Press Enter</p> <button id='btnReset' onclick='resetPage()'>Reset</button> </div>:in-range - 提供与上述类似的功能:

:out-of-range

:in-range {
  border-color: green;
}
:out-of-range {
  border-color: red;
}
:in-range {
  border-color: green;
}
:out-of-range {
  border-color: red;
}

JS Fiddle demo

参考文献:

  • CSS:
  • JavaScript的:
    • Element.classList API
    • for (initialisation; assessment; change) {...} loop
    • HTMLInputElement - <div id='nav'> <label for='speed'>&nbsp;Speed <br /> <input type='number' class='C1' id='speed' placeholder='1-10' max='10' min='1' /> </label> <br /> <label for='Iron'>&nbsp;Iron <br /> <input type='number' class='C1' id='Iron' placeholder='1-5' max='5' min='1' /> </label> <br /> <label for='Ice'>&nbsp;Ice <br /> <input type='number' class='C1' id='Ice' placeholder='1-5' max='5' min='1' /> </label> <br /> <label for='Mass'>&nbsp;Mass <br /> <input type='number' class='C1' id='Mass' placeholder='1-5' max='5' min='1' /> </label> <br /> <label for='Diameter'>&nbsp;Diameter <br /> <input type='number' class='C1' id='Diameter' placeholder='1-5' max='5' min='1' /> </label> <br /> <p id='spacer'>&nbsp;</p> <p id='enterSign' onclick='saveitem()'>Press Enter</p> <button id='btnReset' onclick='resetPage()'>Reset</button> </div>的(有限)信息。
    • parseInt()

答案 1 :(得分:1)

你应该考虑整个方法,因为在我看来,在keyup上循环遍历所有输入元素是不必要的。也许使用focus out事件或类似事件。

但是要回答你的问题,既然你检查输入onkeyup的值,为什么不在检查后操纵这个元素的样式:

window.onkeyup = function(e) {
     var formValid = true;

     var inputs = document.getElementsByClassName("C1");
     for (i = 0; i < inputs.length; i++) {
         inputsVal = inputs[i].value;
         if (!inputsVal || inputsVal == "" || inputsVal == " ") {
              formValid = false;
              inputs[i].style.borderColor= "red";
         } else {
              inputs[i].style.borderColor= "green";
         }
     }

     document.getElementById('enterSign').style.display = "block";
     document.getElementById('spacer').style.display = "none";
     if (event.which == 13) {
         saveitem();
     }

     return formValid;
};

但是,这会在每次按键后立即改变所有输入的颜色。

这是一个小例子: https://jsfiddle.net/hu2amocq/

另外需要提及的一点是:由于您使用input type="number",大多数浏览器都会向表单元素添加控制按钮,您可以在小提琴中看到。使用这些来增加/减少数字不会触发您的window.onkeyup事件。

更好的方法

正如我在开始时所说,你应该考虑你的概念,只在必要时评估输入,只改变一个输入。

查看http://www.w3schools.com/jsref/dom_obj_event.asp并使用其中列出的其中一个事件。例如:

<input type="number" onkeyup="validate('speed')" id="speed" />

validate = function(id) {
      var input = document.getElementById(id);
      var value = input.value.trim();
      if (value && value.length > 0) {
          document.getElementById(id).style.borderColor = "green";
      } else {
          document.getElementById(id).style.borderColor = "red";
     }
 }

答案 2 :(得分:1)

https://jsfiddle.net/t3ktjez2/

你想做这样的事情,你把事件绑定到每个输入,这样他们就可以单独处理它们,而不是在按下窗口的所有按钮上循环它们。

var inputs = document.getElementsByClassName('C1');
for (var i = 0; i < inputs.length; i++) {
    inputs[i].addEventListener("keyup", function(e) {
        var input = e.target;
        // Check for number
        if (e.target.value) {
            input.style.borderColor= "green";
        } else {
             input.style.borderColor= "red";
        }
    });   
}

修改 实际上,执行此操作的最佳方法是让keyup事件冒泡到#nav元素,然后在那里进行检查。

https://jsfiddle.net/t3ktjez2/1/

这意味着您不必将许多事件绑定到每个输入,而是使用检查哪个事件来查看导致keyup事件的元素。

var nav = document.getElementById('nav');
nav.addEventListener("keyup", function(e) {
    var el = e.target;
    if (el.className === 'C1') {
        // The element that trigger this event is an input so do check
        if (el.value) { // Do a real value check here
            el.style.borderColor = "green";
        } else {
            el.style.borderColor = "red";
        }   
    }
});   

答案 3 :(得分:1)

首先,我将事件绑定到输入字段而不是窗口。这样你就不会监听每个onkeyup事件。然后你必须得到最小值和最大值,比较它们并使颜色(css /样式)发生变化。

这是一个不完整的例子。不完整我的意思是它不会处理所有场景 - 例如使用向上和向下按钮并编写文本而不是数字。但它会让你知道如何实现这一点。它当然也符合你的要求:)

注意:我创建了两个无效且有效的css类。我相信样式应该由css完成,而不是javascript - 类很适合这个。

var inputs = document.getElementsByClassName('C1');

for (var j = 0; j < inputs.length; j++){
  var input = inputs[j];
  input.addEventListener('keyup', function(e){
    var ele = e.target;
    var inputsVal = ele.value;

    var min = parseInt(ele.getAttribute("min"));
    var max = parseInt(ele.getAttribute("max"));

    console.log(ele, inputsVal, min, max);
    if (inputsVal && inputsVal <= max && inputsVal >= min) {
      ele.classList.add('valid');
      ele.classList.remove('invalid');
    }else {
      ele.classList.add('invalid');
      ele.classList.remove('valid');
    }
  });
}

&#13;
&#13;
var inputs = document.getElementsByClassName('C1');

for (var j = 0; j < inputs.length; j++){
  var input = inputs[j];
  input.addEventListener('keyup', function(e){
    var ele = e.target;
    var inputsVal = ele.value;
    
    var min = parseInt(ele.getAttribute("min"));
    var max = parseInt(ele.getAttribute("max"));
    
    console.log(ele, inputsVal, min, max);
    if (inputsVal && inputsVal <= max && inputsVal >= min) {
      ele.classList.add('valid');
      ele.classList.remove('invalid');
    }else {
      ele.classList.add('invalid');
      ele.classList.remove('valid');
    }
  });
}
&#13;
.invalid {
 border-color:red; 
  }

.valid{
  border-color:green;
  }
&#13;
<div id='nav'>
  <label for='speed'>&nbsp;Speed
    <br />
    <input type='number' class='C1' id='speed' placeholder='1-10' max='10' min='1' />
  </label>
  <br />
  <label for='Iron'>&nbsp;Iron
    <br />
    <input type='number' class='C1' id='Iron' placeholder='1-5' max='5' min='1' />
  </label>
  <br />
  <label for='Ice'>&nbsp;Ice
    <br />
    <input type='number' class='C1' id='Ice' placeholder='1-5' max='5' min='1' />
  </label>
  <br />
  <label for='Mass'>&nbsp;Mass
    <br />
    <input type='number' class='C1' id='Mass' placeholder='1-5' max='5' min='1' />
  </label>
  <br />
  <label for='Diameter'>&nbsp;Diameter
    <br />
    <input type='number' class='C1' id='Diameter' placeholder='1-5' max='5' min='1' />
  </label>
  <br />
  <center>
    <p id='spacer'>&nbsp;</p>
    <p id='enterSign' onclick='saveitem()'>Press Enter</p>
  </center>
  <center>
    <button id='btnReset' onclick='resetPage()'>Reset</button>
  </center>
</div>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

你可以使用jQuery并监听输入上的模糊

Fiddle

jQuery('input[type=number]').on('blur',function(){
var min = $(this).attr('min');
var max = $(this).attr('max');
if(min <= $(this).val() && $(this).val() <= max ) $(this).css('border','1px solid green');
});

这只是建议:)