user2719152
user2719152

Reputation: 989

select from large number of options

I want to make a select field in html. This field will have values from 1 to 27 to select. So i want to try some some sort method rather than typing manually for 27 values. Is it possible with the help of java script or something? I am not an expert in front end technologies so be generous please.

Upvotes: 1

Views: 1517

Answers (2)

Vertical3
Vertical3

Reputation: 88

Well, you CAN if you want to...

The HTML

<select id="mySelect" name="mySelect"></select>

Pure Javascript:

var values = ['something', 'something else', 'some other thing']; var mySelect = document.getElementById('mySelect');

for (var i=values.length;i--;){
  var optionElem = document.createElement('option');
  optionElem.setAttribute('value', value[i]);
  var optionText = document.createTextNode(value[i]);
  optionElem.appendChild(optionTect);
  mySelect.appendChild(optionElem);
}

Or you could use jQuery:

var values = ['something', 'something else', 'some other thing'];

    $.each(values, function(idx, value) {
        var optionElem = '<option value="' + value + '">' + value + '</option>';
        $('#mySelect').append(optionElem);
    });

Still this is usually a silly thing to do unless you need them to be dynamically generated.

Upvotes: 1

Err
Err

Reputation: 920

I'm not sure if you are trying to list 1 to 27 in dropdown or trying to simply list 27 items. In either case these are both. This is using basic JavaScript.

Demo: https://jsfiddle.net/0zy7655z/

Lists 27 times

var vals = ['item1','item2','item3','etc.'];
var sel1 = document.getElementById('list1');
vals.forEach(function(val,ind) {
  var opt = document.createElement('option');
  opt.text = val;
  opt.value = ind;
  sel1.appendChild(opt);
});

Lists 1 to 27

var sel2 = document.getElementById('list2');
for (var i = 1; i <= 27; i++) {
  var opt = document.createElement('option');
  opt.text = i;
  opt.value = i;
  sel2.appendChild(opt);
}

Upvotes: 2

Related Questions