mar
mar

Reputation: 161

how to use arrays within select dropdown select

I am trying to populate a dropdown select with an array using jQuery.

Here is my code:

<div class="form-group row">
    <label class="col-xl-3 col-lg-3 col-form-label">Numbers</label>
    <div class="col-lg-9 col-xl-6">
        <div class="form-inline">
            <select name="sabb" class="req form-control form-control-lg form-control-solid" id="age-range-2" autocomplete="off" required />
            </select>

            <label class="col-xl-1 col-lg-1 col-form-label">to</label>

            <select name="eabb" class="req form-control form-control-lg form-control-solid" id="second-2" autocomplete="off" required />
            </select>
        </div>
    </div>
</div>
                                          

My accompanying jQuery is as follows:

$(function() {
    var $select = $("#age-range-2");
    for (i = 18; i <= 60; i++) {
        $select.append($('<option></option>').val(i).html(i))
    }

    $("#age-range-2").change(function() {
        var val = parseInt($("#age-range-2").val());
        $("#second-2").html("");
        for (i = val + 1; i <= 60; i++) {
            $("#second-2").append("<option value='" + i + "'>" + i + "</option>");
        }
    });
});

I am trying to add an array that includes numbers and letters instead of a for loop which should be something like this: var numbers = [1K, 2K, 3K, 4K, 5K];

Here is a visual:

enter image description here

Upvotes: 0

Views: 74

Answers (1)

AnasSafi
AnasSafi

Reputation: 6224

I think this what you need:

for (i = 1; i <= 50; i++) {
     var o = new Option( i + "K", i);
      $(o).html( i + "K");
      $("#age-range-2").append(o);
}

for (i = 18; i <= 60; i++) {
     var o = new Option( i + "K", i);
      $(o).html( i + "K");
      $("#second-2").append(o);
}

You can see result in JSFiddle here


Edited:

If you need predefined array:

var numbers = [1,4,8,14,20,50,100];

$.each(numbers, function( index, value ) {
  var o = new Option( value + "K", value);
      $(o).html( value + "K");
      $("#age-range-2").append(o);
});

Upvotes: 1

Related Questions