2

I have a requirement with the Textbox . When ever I put some values there should be some validation to put "-" in between the values.

Like When I put the value 123456789 in the textbox , it will show me automatically "123-45678-9" or any other format depend upon the business. I am clueless what to do. I need to show "-" while typing value in textbox.

Any idea/ suggession would be helpful.

s_k_t
  • 689
  • 1
  • 15
  • 36
  • Have you tried something so far? – Alvaro Flaño Larrondo Jun 26 '15 at 20:02
  • onKeyPress event u can do that, after how many characters u have to do it – Narendra Jaggi Jun 26 '15 at 20:05
  • every 3 element I need to do . – s_k_t Jun 26 '15 at 20:06
  • First read about the `.change()` event handler: https://api.jquery.com/change/ then combine that with `String.match()` function http://www.w3schools.com/jsref/jsref_match.asp and you're done pretty much – Schlaus Jun 26 '15 at 20:08
  • I tried this $(document).ready(function(){ $("#autoCompleteID").on("keyup",function(event) { /* Act on the event */ var value = $("#autoCompleteID").val(); console.log(value); if(value.length==3 || value.length==6){ value = value+"-"; $("#autoCompleteID").val(value); } }); }); – s_k_t Jun 26 '15 at 20:26
  • but the problem is that when I do fast typing it is not working.. – s_k_t Jun 26 '15 at 20:27

2 Answers2

0

Please have look @ this, customize it according to your need

    <!DOCTYPE html>
<html>
<body>

<input type="text" id="myid" onkeyup="myFun()">


<script>
var counter = 0;
function myFun() {

    counter++;
    if(counter==3)
    {
       var value = document.getElementById("myid").value;
       value = value + "-";
       document.getElementById("myid").value = value;
       counter=0;
    }
}
</script>

</body>
</html>
Narendra Jaggi
  • 1,297
  • 11
  • 33
0

It depends on which element tag you are using.

If you are using , then you can use the pattern attribute and regex. I am a bit confused as to what you want exactly; however, here is an example of how to only accept a number like 123-45678-9 in that exact format of 3 numbers then a dash the 5 numbers then a dash and then one number.

[0-9]{3}-[0-9]{5}-[0-9]{1} This says it will accept any number, the [0-9], for the first 3 spots, {3} with the first number being the minimum and a potential second number being the maximum number of consecutive numbers, then a dash, -, and so on with those rules changing slightly with {5} and {1}.

However, if you only want to include dashes and numbers in your input, you could just use the following regex: "[0-9]|-"

In the end your solution might look something like:

If you are using , there is no pattern attribute you an apply to the element and you will have to use javascript to restrict what type of input pattern to accept.

Stan Liu
  • 190
  • 2
  • 8