Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Drop-Down list (<select>) programmatically?

I want to create a function in order to programmatically add some elements on a page.

Lets say I want to add a drop-down list with four options:

<select name="drop1" id="Select1">   <option value="volvo">Volvo</option>   <option value="saab">Saab</option>   <option value="mercedes">Mercedes</option>   <option value="audi">Audi</option> </select> 

How can I do that?

like image 427
Christos Baziotis Avatar asked Jun 08 '13 17:06

Christos Baziotis


People also ask

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

STEP 1 − Create a select tag with multiple options and assign an id to the select tag. STEP 2 − Also, create an empty DOM with an id to display the output. STEP 3 − Let there be a button element for the user to click and see the option selected. STEP 4 − Let the user select an option from the dropdown list.

How do you create a dropdown list in JavaScript?

Example Explained Use any element to open the dropdown menu, e.g. a <button>, <a> or <p> element. Use a container element (like <div>) to create the dropdown menu and add the dropdown links inside it. Wrap a <div> element around the button and the <div> to position the dropdown menu correctly with CSS.

How can get xpath for dropdown value?

To get an XPATH of an element right-click the Dropdown menu and select 'Inspect element with Firebug'. Then corresponding code would be highlighted in the firebug, right-click on it and select copy XPath. By this method we can copy the XPATH and paste it into the Selenium IDE tool's Target section.


1 Answers

This will work (pure JS, appending to a div of id myDiv):

Demo: http://jsfiddle.net/4pwvg/

var myParent = document.body;    //Create array of options to be added  var array = ["Volvo","Saab","Mercades","Audi"];    //Create and append select list  var selectList = document.createElement("select");  selectList.id = "mySelect";  myParent.appendChild(selectList);    //Create and append the options  for (var i = 0; i < array.length; i++) {      var option = document.createElement("option");      option.value = array[i];      option.text = array[i];      selectList.appendChild(option);  }
like image 178
tymeJV Avatar answered Sep 28 '22 05:09

tymeJV