0

I have three inputs for telephone numbers that each have its length of 4,8,4 repectively. I handle the focus of mouse through jQuery when maxlength of input field is reached then focus/jump to the next field.

I also want to do a beside focus to count the digits in each field if they are less then maxlength then append zeros on the left side to make it equal to the maxlength of respective input fields when we echo the entered field. e.g if in first input someone enters only two digits like 47 then the output should be 0047 with two appended zeros on the left side after echo.

Here is my HTML:

<form>
<input type="text" name="area_code" id="area_code" maxlength="4" size="3" /> -
<input type="text" name="number1" id="number1" maxlength="8" size="8" /> -
<input type="text" name="number2" id="number2" maxlength="4" size="3" />
</form>

here is the jquery

<script type="text/javascript" src="js/jquery.autotab-1.1b.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#area_code, #number1, #number2').autotab_magic().autotab_filter('numeric');
});
</script>
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Kashif Waheed
  • 31
  • 1
  • 1
  • 8

3 Answers3

1

You've got PHP and jQuery tags on the question so here's both :

PHP : str_pad

jQuery : There's no built in function as far as I know so you will have to create one. Here is a question about doing it in javscript. Adding extra zeros in front of a number using jQuery? the accepted answer should do the trick.

Community
  • 1
  • 1
piddl0r
  • 2,431
  • 2
  • 23
  • 35
  • str_pad() is used for strings i mean it appends zeros to string but what in my case is the input take numeric digits so it do not append zeros with numeric digit so any function for digits?? – Kashif Waheed Apr 11 '13 at 12:03
0
var num1 = $('#number1');
var diff1 = 0;

if (num1.value.length < num1.attr('maxlength')) 
 { diff1 = num1.attr('maxlength') - num1.value.length; }

for (var i = 0; i< diff1; i++ ) { num1.val = '0' + num1.val(); } 
David Houde
  • 4,835
  • 1
  • 20
  • 29
0

You could always write a function to do it for you:

$('#area_code, #number1, #number2').blur(function(){
    $(this).val(padMe($(this).val(),$(this).attr("maxlength")));
});

function padMe(str,length)
{
    var diff = length-str.length;
    return (diff>0) ? (new Array( diff+1 ).join("0") + str) : str;
}
MasNotsram
  • 2,105
  • 18
  • 28