Reputation: 1242
I am new to JQuery and i am looking for a script which fulfills the below need.
User has to type a number input in the textbox say:456 (Can be input of any length) the value has to change to 000000000000000456 (length has to be 18 with zeros appended in front of the user input).
Eg: 12 has to change to 000000000000000012
145 has to change to 000000000000000145
Function has to be invoked on click of button. Below is the snippet:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<title></title>
<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script>
$(document).ready(function () {
$("#acb1").click(function () {
});
});
</script>
</head>
<body>
<form id="form1">
<div>
<input type="text" id="ac1" value=""/>
<input type="button" id="acb1" value="Search" />
</div>
</form>
</body>
</html>
Any leads would be appreciated.
Thanks
Upvotes: 0
Views: 215
Reputation: 913
Try this
$(document).ready(function () {
$("#acb1").click(function () {
var len = $("#ac1").val().length;
if (len < 18 && len > 0)
{
var temp = '';
for (var i = 0; i < 18 - len; i++)
{
temp += '0';
}
temp +=$("#ac1").val();
$("#ac1").val(temp);
}
});
});
Upvotes: 0
Reputation: 37
$("#acb1").click(function () {
var inp = $('#ac1').val();
var limit = 18;
var inpLen = inp.length;
var res = '';
for(var i=0;i<(limit-inpLen);i=i+1){
res = res + '0';
}
res = res + inp;
});
Good luck ;)
Upvotes: 0
Reputation: 2040
You could use a JavaScript for
loop to increment zeroes in front of the string until the variable.length === 18
. Tell me if you need an example. :)
Here is an example (using Manuels function): http://jsfiddle.net/BX5Xs/1/
Upvotes: 0
Reputation: 583
This has been asked and answered before. You are wondering how to create a zero-filled String of the number in your input field. This is the proposed function by Peter Bailey:
function zeroFill( number, width )
{
width -= number.toString().length;
if ( width > 0 )
{
return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
}
return number;
}
In your case you can use it this way:
$(document).ready(function () {
$("#acb1").click(function () {
var num = this.value;
var padded_num = zeroFill(num, 18);
alert('Zero padded number: ' + padded_num);
});
});
Upvotes: 0
Reputation: 10305
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
alert(pad(145, 18));
Upvotes: 1