最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How to auto add a hyphen in user input using Javascript? - Stack Overflow

programmeradmin1浏览0评论

I am trying to validate and adjust user input for a zip code to match the format: xxxxx OR xxxxx-xxxx Is there a simple way using javascript to add the hyphen (-) automatically if the user enters more than 5 digits?

I am trying to validate and adjust user input for a zip code to match the format: xxxxx OR xxxxx-xxxx Is there a simple way using javascript to add the hyphen (-) automatically if the user enters more than 5 digits?

Share Improve this question asked Mar 16, 2019 at 17:04 Anna NguyenAnna Nguyen 431 silver badge11 bronze badges 1
  • github./RobinHerbots/Inputmask refer – prasanth Commented Mar 16, 2019 at 17:14
Add a ment  | 

4 Answers 4

Reset to default 2

Pretty sure there is! Just gotta check how many characters the inputted string has, and if it's 5, add a hyphen to the string :)

var input = document.getElementById("ELEMENT-ID");
input.addEventListener("input", function() {
  if(input.value.length === 5) {
    input.value += "-";
  }
}

Try the following.

function add_hyphen() {
    var input = document.getElementById("myinput");
    var str = input.value;
    str = str.replace("-","");
    if (str.length > 5) {
        str = str.substring(0,5) + "-" + str.substring(5);
    }
    input.value = str
}
<input type="text" id="myinput" value="a" OnInput="add_hyphen()"></input>

Anna,

The best way to do it would be to use a regular expression. The one you'll need is:

^[0-9]{5}(?:-[0-9]{4})?$

You would ten use something like:

function IsValidZipCode(zip) {
        var isValid = /^[0-9]{5}(?:-[0-9]{4})?$/.test(zip);
        if (isValid)
            alert('Valid ZipCode');
        else {
            alert('Invalid ZipCode');
        }
    }

In your HTML call it like this:

<input id="txtZip" name="zip" type="text" /><br />
<input id="Button1" type="submit" value="Validate"
onclick="IsValidZipCode(this.form.zip.value)" />

For more on Regular Expressions this is a good article:

Regular Expressions on Mozilla Developers Network

You can try using simple javascript function as follows

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">

  <title>JS Bin</title>
  <script>
    function FN_HYPEN(){
    var input = document.getElementById("USER");

  if(input.value.length === 5) {
    input.value += "-";
  }

                       }
  </script>
</head>
<body>
<INPUT ID="USER" TYPE="TEXT" onKeypress="FN_HYPEN();"/>
</body>
</html>
发布评论

评论列表(0)

  1. 暂无评论