我有一个用户输入数字的表单。单击时会调用一个函数。我想突出显示并清空所有无效字段(非数字字段)。到目前为止,它突出并清除了所有输入。我只需要那些没有填写的,或者输入不是数字的那些。
function validatefilledIn() {
"use strict";
var arr = document.getElementsByName('qty');
var score = document.getElementById('total');
for(var i=0; i<arr.length;i++){
if(isNaN(parseInt(arr[i].value))) {
alert("Please make sure all the fields are filled in.");
$('input').val('').css( "border-color", "red" );
$('#form1').find('#total').val('');
return false;
}
}
}
<form name="myForm" id="form1">
<fieldset>
<input type="text" name="qty" id="qty1" oninput="findTotal()" class="hvr-pop" required/>
<input type="text" name="qty" id="qty2" oninput="findTotal()" class="hvr-pop" required/>
<input type="text" name="qty" id="qty3" oninput="findTotal()" class="hvr-pop" required/>
<input type="text" name="qty" id="qty4" oninput="findTotal()" class="hvr-pop" required/>
<input type="text" name="qty" id="qty5" oninput="findTotal()" class="hvr-pop" required/>
<input type="text" name="qty" id="qty6" oninput="findTotal()"class="hvr-pop" required/>
</fieldset>
</form>
答案 0 :(得分:0)
使用if(isNaN(arr[i].value) || arr[i].value == "")
确实有效!
function validatefilledIn() {
var arr = document.getElementsByName('qty');
for(var i=0; i<arr.length;i++){
if(isNaN(arr[i].value) || arr[i].value == "") {
$(arr[i]).val('').css( "border-color", "red" );
}
}
}
完整HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
function findTotal() {
}
function validatefilledIn() {
var arr = $("[name='qty']");
$.each(arr, function(i, o) {
if(isNaN($(o).val()) || $(o).val() == "") {
$(o).val('').css( "border-color", "red" );
} else {
$(o).css( "border-color", "green" );
}
});
}
</script>
<form name="myForm" id="form1">
<fieldset>
<input type="text" name="qty" id="qty1" oninput="findTotal()" class="hvr-pop" required/>
<input type="text" name="qty" id="qty2" oninput="findTotal()" class="hvr-pop" required/>
<input type="text" name="qty" id="qty3" oninput="findTotal()" class="hvr-pop" required/>
<input type="text" name="qty" id="qty4" oninput="findTotal()" class="hvr-pop" required/>
<input type="text" name="qty" id="qty5" oninput="findTotal()" class="hvr-pop" required/>
<input type="text" name="qty" id="qty6" oninput="findTotal()" class="hvr-pop" required/>
</fieldset>
<button onClick="validatefilledIn()">Check</button>
</form>
</body>
</html>