Prepend zeroes to a number ('-' * 26) Using JavaScript to prepend zeroes to a number, for example: 0005 instead of 5 or Using JavaScript to prepend zeroes to a number, for example: 0099 instead of 99.
A Pen by Siôn J. Lewis on CodePen.
<span>Max num of zeros to pad by: </span><input id="numZeros" type="number" value="3" /><br /> | |
<span>Enter your number: </span><input id="numInput" type="number" value="5" /><br /> | |
<br /> | |
<span>Output: </span><label id="lblOutput"></label><br /> | |
<br /> | |
<button id="btnSubmit" type="submit" onclick="javascript:SJL.click_Submit();return false;">Submit</button><br /> |
Prepend zeroes to a number ('-' * 26) Using JavaScript to prepend zeroes to a number, for example: 0005 instead of 5 or Using JavaScript to prepend zeroes to a number, for example: 0099 instead of 99.
A Pen by Siôn J. Lewis on CodePen.
if (SJL === undefined || typeof (SJL) !== 'object') { var SJL = new Object(); } | |
SJL = function () { | |
var self = {}; | |
// This funxtion does the work... | |
self.prependZeroes = function (str, maxLength) { | |
// Keep calling its self until the string length is meet. | |
return str.length < maxLength ? self.prependZeroes("0" + str, maxLength) : str; | |
} | |
// ------------------------------ | |
self.click_Submit = function () { | |
var numInput = $('#numInput').val(); | |
var numZeros = $('#numZeros').val(); | |
var output = self.prependZeroes(numInput, numZeros); | |
$('#lblOutput').html(output); | |
} | |
return { | |
click_Submit: function () { | |
return self.click_Submit(); | |
} | |
} | |
}(); |
span { | |
display:inline-block; | |
width:200px; | |
} |