Baqer Naqvi
Baqer Naqvi

Reputation: 6504

How to change the width of dynamically created dropdown?

I have created dropdown dynamically, trying to set its size but failed...

code

var L = document.createElement('label');
    L.id = 'L_range';
    var S = document.createElement('select');
    S.id = 'range';
    var op1 = document.createElement('option');
    var op2 = document.createElement('option');
    var op3 = document.createElement('option');
    var op4 = document.createElement('option');
    op1.appendChild(document.createTextNode('10'));
    op1.id = '10';
    op2.appendChild(document.createTextNode('25'));
    op2.id = '25';
    op3.appendChild(document.createTextNode('50'));
    op3.id = '50';
    op4.appendChild(document.createTextNode('100'));
    op4.id = '100';
    S.appendChild(op1);
    S.appendChild(op2);
    S.appendChild(op3);
    S.appendChild(op4);
    L.appendChild(S);
    L.appendChild(document.createTextNode('records per page'));
    var root = document.getElementById('sel');
    root.innerHTML = '';
    root.appendChild(L);

I have tried S.size = '1'; but there's no difference.

Upvotes: 0

Views: 3041

Answers (2)

kasper Taeymans
kasper Taeymans

Reputation: 7026

http://jsfiddle.net/LcC9W/

jquery

var values=[0,1,2,3,500,700,100,565,475,52556,5225,1111];

$.each(values, function(k,v){
    $('#myselect').append($('<option>').val(v).html(v));
});
$('#myselect').css('width','200px');

html

<select id="myselect"></select>

ps: don't forget to place this code in a document ready function, otherwise it will not be triggered. (this is not needed in jsfiddle)

var values=[0,1,2,3,500,700,100,565,475,52556,5225,1111];

$(function(){

    $.each(values, function(k,v){
        $('#myselect').append($('<option>').val(v).html(v));
    });
    $('#myselect').css('width','200px');
})

Upvotes: 1

Alex
Alex

Reputation: 10216

the size attribute does not handle the select's width. it just defines how many entries will be visible vertically, adding a scrollbar if needed (try the demo).

Just give it a width via css and you're good to go, look at this fiddle

<select style="width: 100px;">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

or via JS:

S.setAttribute('style', 'width:10px');

Upvotes: 1

Related Questions