Javascript Input Mask / Javascript Input Filtreleme

Bir iş dolayısı ile Prototype framework ile entegre çalışan bir input filtreleme / mask kodu yazmam gerekti , araştırmalarımda tamamen dinamik bir filtreleme sistemi bulamadım dedim ki yazmak gerek ve yazdım. Sonuçta ortaya böyle bir şey çıktı.

Gerekli olan : Prototype JavaScript framework, version 1.6.0.2

Kod :

JAVASCRIPT:
  1. if ( typeof(My) === 'undefined' ) {
  2.         My = new Object();
  3.     }
  4.    My.Mask = {
  5.         install:function() {
  6.             var elements = $$('input[mask]');
  7.             elements.each(function(item) {
  8.                  Event.observe(item, 'keypress',My.Mask.setMask.bindAsEventListener(item), true);
  9.             });
  10.         },
  11.         mask:{
  12.                 format:'',
  13.                 regex:''
  14.             },
  15.         setMask:function(event) {
  16.             var mask_code   = this.readAttribute("mask");
  17.             var mask_sys    = mask_code.split("|");
  18.             var mask = My.Mask.mask;
  19.             mask.format = mask_sys[1].replace(/#/g,' ');
  20.             if(mask_sys[0] == "number") {
  21.                 mask.regex = /\d/;
  22.             }else if(mask_sys[0] == "all") {
  23.                 mask.regex = /\w/;
  24.             }else if(mask_sys[0] == "char") {
  25.                 mask.regex = /[a-zA-Z]/;
  26.             }
  27.            
  28.             var keyCode = My.Mask.getKeyPress(event);
  29.        
  30.             if(My.Mask.notChar(keyCode)) {
  31.                 var chr     = String.fromCharCode(keyCode);
  32.                 var strng   = this.value + chr;
  33.                 var pos     = strng.length;
  34.                 if ( mask.regex.test(chr) && pos <= mask.format.length ) {
  35.                    if ( mask.format.charAt(pos - 1) != ' ' ) {
  36.                       strng = this.value + mask.format.charAt(pos - 1) + chr;
  37.                    }
  38.                    this.value = strng;
  39.                 }
  40.                Event.stop(event);
  41.             }
  42.            
  43.         },
  44.         getKeyPress: function(e) {
  45.           return window.event ? window.event.keyCode
  46.                : e            ? e.which
  47.                :                0;
  48.         },
  49.         notChar: function(key) {
  50.             return ( key>= 32 && key <127 );
  51.         }
  52.    }

Örnek Kullanım:

Body tagı :

HTML:
  1. <body onload="My.Mask.install()">

Input tagı :

HTML:
  1. <input id="input_time" type="text" mask="number|+##(###)###-####" />

convert this post to pdf.
Etiketler : Javascript, , ,

Leave a Reply




*
To prove you're a person (not a spam script), type the answer to the math equation shown in the picture. Click on the picture to hear an audio file of the equation.
Click to hear an audio file of the anti-spam equation