Reputation: 1008
How can I loop from A to Z? I'd like to populate a select menu with the letters of the alphabet, eg
<select>
<option>A</option>
<option>B</option>
<option>C</option>
...
<option>Z</option>
</select>
Upvotes: 9
Views: 27354
Reputation: 2500
Using ascii value of A to Z, append options in select using jQuery
for (var i = 65; i <= 90; i++) {
$('#select').append('<option>' + String.fromCharCode(i) + '</option>');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id='select'>
</select>
Upvotes: 0
Reputation: 5738
"<option>"+"ABCDEFGHIJKLMNOPQRSTUVWXYZ".split('').join("</option><option>")+"</option>"
const select = document.createElement("select"); /* select your 'select' tag instead*/
select.style.width = "100px"; /* for demo */
select.innerHTML =
"<option>"+"ABCDEFGHIJKLMNOPQRSTUVWXYZ".split('').join("</option><option>")+"</option>";
/* to generate A-Z options */
document.body.appendChild(select);
Upvotes: 1
Reputation: 23693
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)
Upvotes: 4
Reputation: 2345
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();
}
Upvotes: 6
Reputation: 3134
Use char codes: JavaScript Char Codes
for (var i = 65; i <= 90; i++) {
$('#select_id_or_class').append('<option>' + String.fromCharCode(i) + '</option>');
}
Upvotes: 27
Reputation: 1008
You can do this with the following
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
$.each(alphabet, function(letter) {
$('.example-select-menu').append($('<option>' + alphabet[letter] + '</option>'));
});
Upvotes: 9