Smegger
Smegger

Reputation: 1008

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>

Upvotes: 9

Views: 27354

Answers (6)

Sahil Thummar
Sahil Thummar

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

nkitku
nkitku

Reputation: 5738

One-Liner and Fastest

"<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

German Attanasio
German Attanasio

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

Borys Generalov
Borys Generalov

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

Bic
Bic

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

Smegger
Smegger

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

Related Questions