Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically choose item in select drop down

Tags:

html

I have a drop down:

<select>
  <option value="1">1</option>
  <option value="2">2</option>
</select>

How would I select item 2 programmatically?

like image 702
CrazyCoder Avatar asked Mar 05 '11 18:03

CrazyCoder


People also ask

How do you display a selected value in a drop-down list?

Method 1: Using the value property: The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.

How do I select text in a drop-down list?

Simply try the following code. var text= $('#yourslectbox'). find(":selected"). text();

How do you pre select a select option?

A select box also called drop down box provides an option to list down various options in the form of drop down list. You can also preselect a value in dropdown list of items in HTML forms. For that, add selected in the <option> tag for the value you want to preselect.


1 Answers

First get a handle on that select somehow:

var select = document.getElementsByTagName("SELECT")[0];

Then manipulate the selectedIndex property (I believe it's a zero-based index):

select.selectedIndex = 1;
like image 82
jpsimons Avatar answered Oct 21 '22 03:10

jpsimons