Ben G
Ben G

Reputation: 26789

Getting <select> to update when you add options

I have a SELECT which looks like this.

<select id="mySelect"><option value="">Please select</option></select>

At a certain point, my javascript sets the OPTION as follows:

var elSel = document.getElementById('mySelect');
elSel.options[0].value = myValue;
elSel.options[0].text = myText;

The problem is that you have to click the select for it to show myText. How do I make it so that myText (with myValue) shows as soon as I run that javascript?

Upvotes: 0

Views: 168

Answers (4)

Ben G
Ben G

Reputation: 26789

The problem was the jQuery plugin I was using (Uniform), I didn't realize that I had to run $.uniform.update()

http://pixelmatrixdesign.com/uniform/

Upvotes: 0

Sebasti&#225;n Grignoli
Sebasti&#225;n Grignoli

Reputation: 33472

Try using DOM manipulation:

<select id="mySelect">
<option value="">Please select</option>
</select>
<script>

var elSel = document.getElementById('mySelect');

var opt = {};


opt = document.createElement('option');
opt.value = '1';
opt.text = 'a';
elSel.appendChild(opt);

opt = document.createElement('option');
opt.value = '2';
opt.text = 'b';
opt.selected = true;       /* Here is where we update the select element */
elSel.appendChild(opt);

opt = document.createElement('option');
opt.value = '3';
opt.text = 'c';
elSel.appendChild(opt);

</script>

Test it here:

http://dl.dropbox.com/u/186012/demos/stackoverflow/select/index.html

Upvotes: 0

Tahbaza
Tahbaza

Reputation: 9546

Add elSel.selectedIndex = 0; to the end of your script. Use elSel.options.length-1 if you're going to ever have more than 1 item and you want to select the last item.

<html>
<head>
<script language="javascript">
function addItem() {
var elSel = document.getElementById('test');
elSel.options[0].value = '1';
elSel.options[0].text = 'new value';
elSel.selectedIndex = 0;
}
</script>
</head>
<body>
<form>
<select id="test"><option value="1">- SELECT AN ITEM -</option></select>
<input type="button" value="Add Item" onclick="addItem();" />
</form>
</body>
</html>

Upvotes: 1

William Niu
William Niu

Reputation: 15853

Load the script with onLoad attribute of the body tag? e.g.

<body onload="initSelect()">

Or simply put the script after the select tag:

<select>...</select>
<script>//code to generate the options</script>

Upvotes: 0

Related Questions