我有一个表单,我需要验证经度和纬度字段。
以下代码适用于捕获keypress
。但是在focusout
部分,有两个问题我无法弄清楚:
1 /它应该取代"不允许"带有''的字段中的字符,不会发生
2 /警报永远不会被触发
代码如下所示:
var allowedLongLat = "0123456789.-";
$("#latitude").keypress( function(e) {
var chr = String.fromCharCode(e.which);
if (allowedLongLat.indexOf(chr) < 0)
{
alert("The character "+chr+" is not allowed in this field!");
return false;
}
});
$(document).on("focusout","#latitude",function(){
var str = $("#latitude").val();
var wrongchars = [];
var wrongalert = "";
for (var i = 0, len = str.length; i < len; i++) {
if (allowedLongLat.indexOf(str[i]) < 0)
{
wrongchars.push(str[i]);
}
}
jQuery.each(wrongchars , function(index, value){
$("#latitude").val( str.replace(\'/\'+value+\'/g\', \'\') );
wrongalert += value;
});
if ( wrongalert.lenght > 1 )
{
alert("The characters "+wrongalert+" are not allowed in this field!");
}
});
我错过了哪些想法?
答案 0 :(得分:1)
在代码中发现了一些错误
$("#latitude").val( str.replace(\'/\'+value+\'/g\', \'\') );
有一些拼写错误,
if ( wrongalert.lenght > 1 )
错字错误,应该是长度。
我做了this jsfiddle。
var allowedLongLat = "0123456789.-";
$(document).on("focusout","#latitude",function(){
var str = $("#latitude").val();
var wrongchars = [];
var wrongalert = "";
for (var i = 0, len = str.length; i < len; i++) {
if (allowedLongLat.indexOf(str[i]) < 0)
{
wrongchars.push(str[i]);
}
}
//console.log(wrongchars);
jQuery.each(wrongchars , function(index, value){
console.log(value);
$("#latitude").val( $("#latitude").val().replace(value, '') ); // I simplified here
wrongalert += value;
});
if ( wrongalert.length > 1 )// here was typo error
{
alert("The characters "+wrongalert+" are not allowed in this field!");
}
});