I made this function to get rid of writing numerical option values in a HTML-select manually.
From what I have seen so far it works as expected. But hints and suggestions are welcome anyway.
// Trying it out.
var selects = document.querySelectorAll('.drop-down');
selects = Array.prototype.slice.call(selects);
createOptions(selects[0], -9, 9, 8);
for (var i = 1; i < selects.length; i++) {
createOptions( selects[i],
i * (-1 * Math.pow(10, i)),
i * Math.pow(10, i));
}
// The actual function ...
// The 1st Parameter is the HTML-element, the
// second is the bottom-limit, the third the
// upper limit.
// The fourth, optional parameter allows to
// define the selected-option.
function createOptions( selectElement,
countOptionsStart,
countOptionsEnd,
preSelected ) {
var bottom = countOptionsStart + '';
var top = countOptionsEnd + '';
var demand; // Count of needed chars.
preSelected = preSelected || 0;
var getLeadingZeros = function(demand, value) {
var chars = value.toString() // Convert to string.
.split(''); // Make an array.
// As long as the count of chars is less then
// the demanded count iterate ...
while (chars.length < demand) {
// If the first element in the array contains
// an minus ('-') then use splice() for to
// add a zero at index 1.
if (chars[0] === '-') {
chars.splice(1, 0, '0');
} else {
// ... otherwise add the zero at the
// beginning.
chars.unshift('0');
}
}
// Concat the array-elements to a string and
// return this string.
return chars.join('');
}
// The longer string is taken.
demand = bottom.length >= top.length ? bottom.length : top.length;
// Constructing at adding the option-elements.
for (var i = countOptionsStart; i <= countOptionsEnd; i++) {
var option = document.createElement('option');
var optionInner;
var innerHTML = i + '';
if (innerHTML.length < demand)
innerHTML = getLeadingZeros(demand, innerHTML);
optionInner = document.createTextNode(innerHTML);
option.setAttribute('value', i);
if (i === preSelected) option.setAttribute('selected', 'selected');
option.appendChild(optionInner);
selectElement.appendChild(option);
}
}
<select class="drop-down"></select>
<select class="drop-down"></select>
<select class="drop-down"></select>
<select class="drop-down"></select>