javascript - removing specific charachter from value of a textfield everytime .val() is called on that textfield ( code should be inside jq plugin ) -


sorry couldn't think of better title ! plus english sucks

her first plugin (basically repackaged js code plugin )

it adds comma , separator value every 3 digit , when types inside textfield

  (function($){        $.fn.num = function(userop){              var options =  $.extend(  {seperator:','} , userop );              $(this).keyup(function(e) {                 var num = $(this).val();                 var nstr = num + '';                 nstr = nstr.replace( /\,/g, "");                 var x = nstr.split( '.' );                 var x1 = x[0];                 var x2 = x.length > 1 ? '.' + x[1] : '';                 var rgx = /(\d+)(\d{3})/;                 while ( rgx.test(x1) ) {                     x1 = x1.replace( rgx, '$1' + options.seperator + '$2' );                 }                 $(this).val( x1 + x2 );              })       }    })(jquery);    $('.number_input').num(); 

but problem if put 123456 in textfield

var n = $('.number_input').val(); console.log(n); 

will return 123,456

which fine suppose numeric value , each time user has extract commas manually running trough like

n = number($.trim(n.replace(/\,/g,''))); 

is there way add line plugin gets executed when runs .val() on textfild ?

basically want write comma remover once not every single time each effected textfield value

if change default .val() method combination of .data(), you'll able want. note change .val() can have undesired effect (mostly when user try override .val() aswell...)

anyway, first thing give data every element active number. in init, add code :

this.data('__numered', true); 

now can detect if element formatting.

then here come tricky part : overriding.

you'll have save old .val() method :

$.fn.__val = $.fn.val; 

then recreate .val() check if numbered item :

$.fn.val = function(set){     if(typeof set === 'undefined'){         if(this.first().data('__numered'))             return number($.trim(this.first().__val().replace(/\,/g,'')));         else             return this.first().__val();      }else         return this.__val(set) } 

fiddle : http://jsfiddle.net/tw77j/1/


Comments

Popular posts from this blog

php - SPIP: From Tag directly to an article -

jquery - isAjaxRequest always return false -

ruby on rails - In a controller spec, how to find a specific tag in the generated view? -