1+ /*
2+ HTML Input Type SerialNumber
3+ GitHub: https://github.com/ish-101/HTML-Input-Type-SerialNumber
4+ Dependency: jQuery 3.x.x
5+ License: GNU GENERAL PUBLIC LICENSE Version 3
6+
7+ Made by Ishpreet Singh Bhasin (ish-101)
8+ Website: http://ishpreet.tech/
9+ */
10+
11+ ( function ( $ )
12+ {
13+ $ . fn . serialnumberinput = function ( user_options )
14+ {
15+ var target = this ;
16+ var options = $ . extend (
17+ {
18+ "separator" : "" ,
19+ "pieces" :
20+ [
21+ ] ,
22+ } , user_options , this . data ( ) ) ;
23+ var digits = [ ] ;
24+ var counter = - 1 ;
25+ $ . each ( options . pieces , function ( i )
26+ {
27+ if ( this . type === "separator" )
28+ {
29+ if ( this . separator === undefined )
30+ {
31+ this . separator = options . separator ;
32+ }
33+ this . length = 1 ;
34+ }
35+ else
36+ {
37+ this . type = "character" ;
38+ if ( this . length === undefined )
39+ {
40+ this . length = 1 ;
41+ }
42+ }
43+ this . length = Number ( this . length ) ;
44+ this . length = Math . max ( this . length , 0 ) ;
45+
46+ for ( var j = 0 ; j < this . length ; j ++ )
47+ {
48+ digits [ counter + j + 1 ] = i ;
49+ }
50+ counter += this . length ;
51+ } ) ;
52+ target . attr (
53+ {
54+ 'minlength' : digits . length ,
55+ 'maxlength' : digits . length ,
56+ } ) ;
57+ function main ( key )
58+ {
59+ var x = target . val ( ) . split ( "" ) ;
60+ var correct ;
61+ var recur = false ;
62+ if ( x . length <= digits . length )
63+ {
64+ for ( var i = 0 ; i < x . length ; i ++ )
65+ {
66+ var regex_string ;
67+ if ( options . pieces [ digits [ i ] ] . type === "character" )
68+ {
69+ regex_string = options . pieces [ digits [ i ] ] . pattern ;
70+ }
71+ if ( options . pieces [ digits [ i ] ] . type === "separator" )
72+ {
73+ regex_string = "[\\" + options . pieces [ digits [ i ] ] . separator + "]" ;
74+ }
75+ correct = RegExp ( regex_string ) . test ( x [ i ] ) ;
76+ if ( ! correct )
77+ {
78+ correct = ( options . pieces [ digits [ i ] ] . type === "separator" ) ;
79+ if ( correct )
80+ {
81+ x [ i + 1 ] = x [ i ] ;
82+ x [ i ] = options . pieces [ digits [ i ] ] . separator ;
83+ recur = true ;
84+ }
85+ else
86+ {
87+ break ;
88+ }
89+ }
90+ }
91+ var y = x . join ( "" ) ;
92+ if ( ! correct )
93+ {
94+ y = y . substring ( 0 , i ) ;
95+ }
96+ if ( ( x . length < digits . length ) && ( ( key !== undefined ) && ( ( key !== "Backspace" ) && ( key !== "Delete" ) ) ) && ( options . pieces [ digits [ x . length ] ] . type === "separator" ) )
97+ {
98+ y += options . pieces [ digits [ x . length ] ] . separator ;
99+ main ( ) ;
100+ }
101+ target . val ( y ) ;
102+ if ( recur )
103+ {
104+ main ( ) ;
105+ }
106+ }
107+ }
108+ target . on ( 'keyup' , function ( e )
109+ {
110+ main ( e . key ) ;
111+ } ) ;
112+ return ;
113+ } ;
114+ } ( jQuery ) ) ;
0 commit comments