我正在使用以下HTML
Level 1: <input type="text" name="benefit_std_level1" maxlength="5" value="0.0" onblur="noSpaceTest();float_5_2_percent(this);" style="width:40px;" class="input nospace">%<br />
Level 2: <input type="text" name="benefit_std_level2" maxlength="5" value="0.0" onblur="noSpaceTest();float_5_2_percent(this);" style="width:40px;" class="input40 nospace">%<br />
Level 3: <input type="text" name="benefit_std_level3" maxlength="5" value="0.0" onblur="noSpaceTest();float_5_2_percent(this);" style="width:40px;" class="input nospace">%<br />
如果用户在三个“级别”字段中的任何一个中输入空格,则数据库中会发生错误。因此,我使用以下脚本检查空格,然后将值更改回默认值“0.0”。
jQuery的:
function noSpaceTest(){
$('.nospace').each(function(){
if ($('.nospace').val() == ' '){
$('.nospace').val('0.0');
}
});
}
最初,在我正在开发的网站中,这确实有效,但仅适用于第一个字段(onBlur将检查并找到空格并将其替换为0.0)但是,现在我无法在JSFiddle中使用它(见下面的链接)
我担心我会遗漏一些明显的东西,但我没有接近一个解决方案。有没有人能提供任何见解?
答案 0 :(得分:4)
删除内联js并改为使用change
事件处理程序:
$('.nospace').on('change', function () {
if(/^\s+$/.test(this.value)) this.value = '0.0';
});
答案 1 :(得分:2)
使用$(this)
:
function noSpaceTest(){
$('.nospace').each(function(){
var $this = $(this);
if ($this.val() == ' '){
$this.val('0.0');
}
});
}
答案 2 :(得分:2)
你离代码工作的距离不远,这里有一个修复:
function noSpaceTest(){
$('.nospace').each(function(){
if ($(this).val() == ' '){
$(this).val('0.0');
}
});
}
答案 3 :(得分:2)
你需要使用this
,对于像' '
这样的多个空格也会失败 -
你可以这样做 -
function noSpaceTest(){
$('.nospace').each(function(){
if ($.trim(this.value) === ''){
$(this).val('0.0');
}
});
}
答案 4 :(得分:1)
尝试使用浮动值
function noSpaceTest() {
$('.nospace').each(function () {
var this_input = $(this);
if (parseFloat(this_input.val()) == undefined || parseFloat(this_input.val()) == NaN || $.trim(this.value) === '') {
this_input.val('0.0');
}
});
}
答案 5 :(得分:1)
$( “无空间”)。模糊(()的函数 {
if ($(this).val().trim() == ''){
$(this).val('0.0');
}
});