0

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

1 Answer 1

1

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);
});
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! How about if I want to incorporate a set array of random numbers & figures combined for eg. (1k, 4k, 10k) etc rather than (1k, 2k, 3k, 4k ...)?
Are the required numbers arranged sequentially or randomly? randomly for e.g (5,2,9,5,5,3,6,8,1), sequentially for e.g: (1,2,4,8,16,32,64)
I will input a set list of numbers eg. 1k, 7k, 22k etc
Well I have modified answer, please see it
You can do that in many ways, one of these: use class instead of id, as this jsfiddle.net/dcrqotsu/1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.