How to make a serial number? with a "-" in the middle

I want to make an HTML form so that users can submit serial code. It looks like this:

XX-XX-XX-XX-XX-XX-XX

But I do not want users to manually enter "-" s.

I have two possible solutions.

  • In my first plan, I do a few <input> for each section. And add a tab index, but it's still too complicated for phone users, because Android does not have a TAB function to scroll through 6 <input> s. This means that they will have to deal with listening to super small input boxes and the sensation of the appearance of a buggy keyboard up and down.

  • I could make the text field be controlled with Javascript and make it check the checkbox and split the code into "-" automatically. But imagine if you have

02-02-03-09-05-06

and you want to change “09”, if the user deletes “9”, it will work and will look like this:

02-02-03-00-50-6

which, in my opinion, is not good enough. I want to make it perfect for the user.

So how do professionals do it? Is it possible that the cursor in plan 1 can automatically move from one <enter> to the next?

+4
source share
2 answers

There is an amazing jquery plugin for this kind of inputs:

http://digitalbush.com/projects/masked-input-plugin/

the code:

First include javascript jQuery files and masked input files.

<script src="jquery.js" type="text/javascript"></script> <script src="jquery.maskedinput.js" type="text/javascript"></script> 

Then call the mask function for those elements that you want to mask.

 jQuery(function($){ $("#date").mask("99/99/9999"); $("#phone").mask("(999) 999-9999"); $("#tin").mask("99-9999999"); $("#ssn").mask("999-99-9999"); }); 

Optionally, if you are not satisfied with the underscore ('_') as a placeholder, you can pass an optional argument to maskedinput.

 jQuery(function($){ $("#product").mask("99/99/9999",{placeholder:" "}); }); 

Optionally, if you want to execute the function after the mask completes, you can specify this function as an optional argument to the maskedinput method.

 jQuery(function($){ $("#product").mask("99/99/9999",{completed:function(){alert("You typed the following: "+this.val());}}); }); 

etc.

+3
source

Just use your own JavaScript. You do not need jQuery for something as simple as this.

What you need to do is check the length of the entered string. If it is 2, 5, 8, 11, ..., automatically add a dash. The following condition will return true for these values: value.length % 3 == 2 . You should check this in the keydown event, as it fires after the user enters something.

 document.getElementById('serial').addEventListener('keydown', function (e) { var value = this.value; // 17 is the max length of the serial XX-XX-XX-XX-XX-XX-XX if (value.length < 17) { if (value.length % 3 == 2 && value.substr(value.length - 1, 1) !== '-') { this.value = this.value + '-'; } } }, false); 

Fiddle

+2
source

Source: https://habr.com/ru/post/1495898/


All Articles