2017-04-04 43 views
0

我需要将输入字段的边框颜色设置为绿色,但只有当此字段中的值为数字时才可以。我怎样才能做到这一点?这是我的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代码吗?

+0

请告诉我们你有什么到目前为止已经试过 –

回答

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

3

我会结合使用正则表达式和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>

相关问题