如何仅为数值设置输入字段的边框颜色?

时间:2017-04-04 19:54:14

标签: javascript jquery html

我需要将输入字段的边框颜色设置为绿色,但仅当此字段中的值为数字时才需要。我怎样才能做到这一点?这是我的HTML:

  <div class="well">
            <input type="text" class="field" value="1245"/><br/><br/>
            <input type="text" class="field" value="efg#21"/><br/><br/>
            <input type="text" class="field" value="34536"/><br/><br/>
            <input type="text" class="field" value="abcd"/><br/><br/>
            <input type="text" class="field" value="12asd"/><br/><br/>
        </div>
    </div>

你可以为此建议一个有效的js / jquery代码吗?

2 个答案:

答案 0 :(得分:3)

我将regex与jQuery结合起来。这也响应了用户的输入。

function validate() {
  $("input").each(function () {
    if ($(this).val().match("^[0-9]+$")) {
      $(this).css("border-color","green")
    } else {
      $(this).css("border-color","red")
    }
  });
}

$("input").on("keyup", validate);
validate()
input {
  border-width:1px;
  border-style:solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="well">
    <input type="text" class="field" value="1245"/><br/><br/>
    <input type="text" class="field" value="efg#21"/><br/><br/>
    <input type="text" class="field" value="34536"/><br/><br/>
    <input type="text" class="field" value="abcd"/><br/><br/>
    <input type="text" class="field" value="12asd"/><br/><br/>
</div>

答案 1 :(得分:1)

您可以使用.css() - 函数的回调来检查值并相应地设置边框:

$("input").css("border", function() {
  return (!isNaN($(this).val())) ? '1px solid green' : '';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="well">
  <input type="text" class="field" value="1245" />
  <input type="text" class="field" value="efg#21" />
  <input type="text" class="field" value="34536" />
  <input type="text" class="field" value="abcd" />
  <input type="text" class="field" value="12asd" />
</div>

参考

isNaN

ternary operator