2016-11-22 128 views
0

我有一个文本字段。我正在文本框中写数字。在我写作时,我想添加千分隔符。我发现这个解决方案:在文本框中输入时添加逗号

HTML:

<input type="text" name= "name1" id="id1" onclick="addComma('id1');"> 
<input type="text" name= "name1" id="id2" onclick="addComma('id2');"> 

JQUERY:

function addComma(id){ 
$("#"+id).keyup(function(event) { 

    // skip for arrow keys 
    if(event.which >= 37 && event.which <= 40) return; 

    // format number 
    $(this).val(function(index, value) { 
    return value 
    .replace(/\D/g, "") 
    .replace(/\B(?=(\d{3})+(?!\d))/g, ",") 
    ; 
    }); 
}); 
} 

这只能有时。有时它根本不显示逗号。

请告诉我我的代码有什么问题。

+1

定义的作品有时“? – Matheno

+1

由于第2行的语法错误,它根本不应该工作。无论如何,在单击输入字段时添加键控处理程序没有任何意义。只需在页面加载中添加键控处理程序。 – JJJ

+1

我建议你在'blur'事件上做这件事。添加逗号作为用户类型将是意想不到的行为,并可能导致混淆。 –

回答

1

这里是解决方案,添加逗号,而在文本框中输入。您需要为每个输入触发keyup事件。

$('input').keyup(function(event) { 
 
    // skip for arrow keys 
 
    if(event.which >= 37 && event.which <= 40) return; 
 

 
    // format number 
 
    $(this).val(function(index, value) { 
 
     return value.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","); 
 
    }); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" name= "name1" id="id1"> 
 
<input type="text" name= "name1" id="id2">

1

我建议你在blur事件上格式化输入值。如果您在用户输入时执行此操作,则会出现意想不到的行为,并可能导致混淆。

另请注意,您的HTML有重复的id属性,这是无效的,也有jQuery和JS的奇怪组合。您应该删除过时的on*事件属性,并使用不显眼的事件处理程序。试试这个:

$('.foo').blur(function() { 
 
    $(this).val(function(i, v) { 
 
    return v.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" name="name1" id="id1" class="foo" /> 
 
<input type="text" name="name2" id="id2" class="foo" />

相关问题