[英]How to validate input fields?
我需要驗證這些輸入字段,
HTML,
<div class="row clearfix">
<ul class="clearfix">
<li><input type="number" id="num1"></li>
<li><input type="number" id="num2"></li>
<li><input type="number" id="num3"></li>
<li><input type="number" id="num4"></li>
</ul>
</div>
CSS,
.row {
display:block;
position:relative;
width:500px;
}
.clearfix:before,.clearfix:after {
visibility: hidden;
display: block;
font-size: 0;
content: " ";
clear: both;
height: 0; display:table;
}
ul {
list-style:none;
display:block;
}
.row ul li { float:left; width:75px; margin-right:2px; }
JS,
$("#num3").on('keypress', function (event) {
var key = event.keyCode || event.charCode;
var maxlength = 4;
var num1 = $("#num1").val().length;
var num2 = $("#num2").val().length;
var num3 = $("#num3").val().length;
var num4 = $("#num4").val().length;
$(this).val($(this).val().replace(/[^0-9\.]/g,''));
if($(this).val().length <= 3){
$('#num3').css('background','#ECECEC');
}else if(($(this).val().length == 4) && (key == 8 || key == 46)){
$('#num3').css('background','#ECECEC');
}
else{
$('#num4').focus();
return false;
}
這是代碼: 演示
你能幫助我嗎?
你是這個意思?
$(function() { $("input[id^='num']").on('keyup', function (event) { var key = event.keyCode || event.charCode; var maxlength = 4; $(this).val($(this).val().replace(/[^0-9\\.]/g, '')); var len = $(this).val().length; if ((len < maxlength) || (len == maxlength && (key == 8 || key == 46))) { $(this).css('background', '#ECECEC'); } else { $(this).css('background', 'white'); $(this).closest("li").next().find("input").focus(); return false; } }); });
.row { display:block; position:relative; width:500px; } .clearfix:before, .clearfix:after { visibility: hidden; display: block; font-size: 0; content:" "; clear: both; height: 0; display:table; } ul { list-style:none; display:block; } .row ul li { float:left; width:75px; margin-right:2px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="row clearfix"> <ul class="clearfix"> <li> <input type="number" id="num1"> </li> <li> <input type="number" id="num2"> </li> <li> <input type="number" id="num3"> </li> <li> <input type="number" id="num4"> </li> </ul> </div>
這有效並且更清潔。
$(document).ready(function(){
$("input").keypress(function(event){
var x = event.which || event.keyCode;
if (x<48||x>57){
return false;
}
console.log(parseInt($(this).attr("id")));
if (($(this).val().length+1)==4){
$(this).parent().next().find("input").focus();
}
});
});
只需將您的輸入ID更改為1,2,3,4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.