如何在输入数字的同时在数字输入字段中添加破折号? [英] How to add dashes into a number input field while entering the number?

查看:180
本文介绍了如何在输入数字的同时在数字输入字段中添加破折号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用java脚本在输入时在每个 4th 数字中的html数字字段中插入破折号。我在on-blur而不是on-key -press,on-key-up等等。但是当我试图将功能更改为按键按下/ on-key-up 事件时,它没有给出预期的结果。



这是我使用的代码。

 < html> 
< head>
< script>
函数addDashes(f)
{
f.value = f.value.slice(0,4)+ - + f.value.slice(4,8)+ - + f.value.slice(8,12);
}
< / script>
< / head>
< body>
电话:< input type ='text'name ='phone'onblur ='addDashes(this)'maxlength ='12'>< BR>
< / body>
< / html>

我是'JavaScript'的初学者。我在哪里做错了?

解决方案

这会起作用。它也支持'删除'号码。



但是,我建议你使用 masking



data-console =truedata-babel =false>

< script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1。 1 / jquery.min.js>< / script>< input type ='text'id =txtPhoneNoname ='phone'maxlength ='14'>< BR>

比开心地帮忙。


I am trying to use java script to insert dashes into a html number field at every 4th digit while entering.I did this in on-blur instead of on-key-press,on-key-up etc.But when I tried to change the function to on-key-press/on-key-up events it is not giving the expected results.

This is the code which I used.

<html>
<head>
<script>
 function addDashes(f)
 {
   f.value = f.value.slice(0,4)+"-"+f.value.slice(4,8)+"-"+f.value.slice(8,12);
 }
</script>
</head>
  <body>
     Phone: <input type='text' name='phone' onblur='addDashes(this)' maxlength='12'><BR>
  </body>
</html>

I am a beginner in 'JavaScript'. Where am I doing wrong?

解决方案

This will work. It also supports 'deletion' of number.

However, I would suggest you using masking

$(document).ready(function () {
    $("#txtPhoneNo").keyup(function (e) {
      if($(this).val().length === 14) return;
      if(e.keyCode === 8 || e.keyCode === 37 || e.keyCode === 39) return;
      let newStr = '';
      let groups = $(this).val().split('-');
      for(let i in groups) {
       if (groups[i].length % 4 === 0) {
        newStr += groups[i] + "-"
       } else {
        newStr += groups[i];
       }
      }
      $(this).val(newStr);
    });
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id="txtPhoneNo" name='phone' maxlength='14'><BR>

If you want a snippet of this using masking, let me know, I'll be more than happy to help.

这篇关于如何在输入数字的同时在数字输入字段中添加破折号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆