How can I loop from A to Z? I\'d like to populate a select menu with the letters of the alphabet, eg
You can do this with the following
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
$.each(alphabet, function(letter) {
$('.example-select-menu').append($('<option>' + alphabet[letter] + '</option>'));
});
One-liner
[..."ABCDEFGHIJKLMNOPQRSTUVWXYZ"].map(v=>`<option>${v}</option>`).join('')
Use char codes: JavaScript Char Codes
for (var i = 65; i <= 90; i++) {
$('#select_id_or_class').append('<option>' + String.fromCharCode(i) + '</option>');
}
You can avoid having numbers like 65
in your code if you just use charCodeAt()
and fromCharCode()
.
Print letters from a
to z
:
for(let i = 'a'.charCodeAt(0); i <= 'z'.charCodeAt(0); i++) {
$('#select_id_or_class').append(
'<option>' + String.fromCharCode(i) + '</option>'
);
}
Or:
const aCharCode = 'a'.charCodeAt(0);
for(let i = aCharCode; i <= (aCharCode + 26); i++) {
$('#select_id_or_class').append(
'<option>' + String.fromCharCode(i) + '</option>'
);
}
If you want the uppercase characters, replace 'a'.charCodeAt(0)
with 'A'.charCodeAt(0)
This answer demonstrates the nice idea that you do not need a hardcoded string. In short:
for (i = 65; i <= 90; i++) {
arr[i-65] = String.fromCharCode(i).toLowerCase();
}