Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop from A to Z in jQuery

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>
like image 993
Smegger Avatar asked May 01 '14 14:05

Smegger


3 Answers

Use char codes: JavaScript Char Codes

for (var i = 65; i <= 90; i++) {
    $('#select_id_or_class').append('<option>' + String.fromCharCode(i) + '</option>');
}
like image 169
Bic Avatar answered Oct 20 '22 08:10

Bic


You can do this with the following

    var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
    $.each(alphabet, function(letter) {
        $('.example-select-menu').append($('<option>' + alphabet[letter] + '</option>'));
    });
like image 9
Smegger Avatar answered Oct 20 '22 09:10

Smegger


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(); }

like image 6
Borys Generalov Avatar answered Oct 20 '22 09:10

Borys Generalov