Create a drop down list with options through document.createElement? - javascript

What I want to achieve is simple: when you press a button, it creates a select element with options. I can do the select element fine, but the option, not so much. I've tried numerous things. Here's the code that I used, with some comments to help out.
<!--This is the element that we append the JavaScript to. The code that achieves the task is at the bottom.-->
<p id="clonePanel"></p>
<script>
//Don't worry about the first pid stuff.
var pid = 0;
function dupPan() {
pid++;
//Here we create a "p" element. The following code is the element's content and specs.
var newPanel = document.createElement("p");
newPanel.id=pid;
//Here we create a "select" element (a drop down list).
var newList = document.createElement("select");
//Here we create a text node.
var newListData = document.createTextNode("Example of option");
//Here we append that text node to our drop down list.
newList.appendChild(newListData);
//Here we append our list to our "p" element.
newPanel.appendChild(newList);
//Finally, we append the "p" element to the document, or the "clonePanel" p element.
document.getElementById("clonePanel").appendChild(newPanel);
}
</script>
Hopefully the comments helped out. What's supposed to happen is that a select element is generated along with a text node. Then the two are appended together. Finally, all that stuff is appended to a p element, which is finally placed into the document. I know I'm doing something wrong.
I think that my method of creating a text node isn't correct. I think there's something else. If you know the answer could you please tell me the correct line of code? That would be great. And yes, I HAVE looked at any sources I can find for help but to no avail.
Thanks for reading and helping me out!

You're appending a text node to a select, which isn't right. You should append an option instead:
var newListData = new Option("my label", "my value");
//Here we append that text node to our drop down list.
newList.appendChild(newListData);
You can instantiate the Option like above as a shortcut, or you can use document.createElement('option') to do it the long way.
It can be simplified further by losing the variable and just directly appending new options:
newList.appendChild(new Option("my label 1", "my value 1"));
newList.appendChild(new Option("my label 2", "my value 2"));
newList.appendChild(new Option("my label 3", "my value 3"));

A select element can only have option or optgroup child elements. To add options using the Option constructor:
var select = document.createElement('select');
// Use the Option constructor: args text, value, defaultSelected, selected
var option = new Option('text', 'value', false, false);
select.appendChild(option);
// Use createElement to add an option:
option = document.createElement('option');
option.value = 'theValue';
option.text = 'the text';
select.appendChild(option);

<span id="minExp"></span>
<script>
var minExp = document.getElementById("minExp");
//Create array of options to be added
var array = ["1","2","3","4","5","6","7","8","9","10","10","12","13","14","15","16","17","18","19","20","21","22","23","24"];
//Create and append select list
var selectList = document.createElement("select");
selectList.setAttribute("id", "minExperience");
selectList.setAttribute("class", "form-control");
selectList.setAttribute("name", "minExperience");
minExp.appendChild(selectList);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.setAttribute("value", array[i]);
option.text = array[i]+' Years';
selectList.appendChild(option);
}
</script>

Related

Javascript unable to append options in "select"

In the below function I am trying to add options in the drop down list that I have on my html page.
function getProcessors(){
var ctrl = document.getElementById("AgentlList");
var option = document.createElement("option");
option.text = "Kiwi";
alert(option.text);
ctrl.append(option.text);
//1. ctrl.append("abc");
//2. ctrl.append("<option value='Auditor1'>abc</option>");
//3. ctrl.add("abc");
}
as you can see in the above code besides the line "ctrl.append(option.text);" I have tried other 3 ways as well (commented out) but none of them works.
Can someone please tell me what is wrong and how can I add options in the combobox of my html page.
Regards,
Premanshu
You're mixing native javascript with jQuery.
You have a native DOM node, and to append it, you'd use appendChild.
To set it's text, you'd use textContent, not text.
function getProcessors(){
var ctrl = document.getElementById("AgentlList");
var option = document.createElement("option");
option.textContent = "Kiwi";
ctrl.appendChild(option);
}
Had you been using jQuery, you could do
function getProcessors(){
var ctrl = $("#AgentlList");
var option = $("<option />");
option.text("Kiwi");
ctrl.append(option);
}

Dynamically creation select box options issue in IE8

I am using the following function to create a add options to my select box
//add options to the requested select box
addOptionsToSelect : function(__enum , obj, selected_value) {
$(__enum).each(function(i){
var optn = new Option(this.text, this.val)
if(selected_value === this.val){ optn.setAttribute('selected', 'selected') }
$(obj)[0].options.add(optn);
});
return obj
}
__enum is the key value pair containing the value and the text that we pass to the select option
obj is the select box obj which is also created dynamically
selected_value is the value that needs to set as selected on the select box.
The problem here is optn.setAttribute('selected', 'selected') works fine in all the browsers expect IE8.
I am looking for a workaround that will allow me to set the selected value in all the browsers dynamically.
I'd add an option to a like so:
var select = document.getElementById("drop-down");
var newOption = document.createElement("option");
newOption.innerHTML = 'hello';
select.appendChild(newOption);
Here's an example: my fiddle

Parse html list with javascript then output drop down

I am trying to write some javascript that will automatically take text in a html ul list and then output it as a drop down. Here is what I have so far: http://jsfiddle.net/KRWHP/
The problem of course is that the code doesnt go through each list item and output it in its own option tag.
$("li").each(function () {
$('<option />').text($(this).text())
.val($(this).text())
.appendTo("select");
});
Your fiddle, re-fiddlified.
Don't need jQuery. Just create a new option node for each element and append that to the select.
var ul = document.getElementsByTagName("ul")[0];
var select = document.getElementsByTagName("select")[0];
[].forEach.call(ul.children, function (el) {
var option = document.createElement("option");
option.textContent = el.textContent;
select.appendChild(option);
});
Example

How to make a selection list to null in runtime?

I have a code that fetches a list from DB. Using that returned array i am creating a grid table and two combo boxes dynamically. Now, the code is working fine for first time. I can also able to add new entry to the database and show it in the grid. Now the problem is with the combo box.
Whenever i add a new entry, the table gets updated by deleting the previous content in the table and fetching again from the DB along with new entry. But the combo options get appended with the newly arrived data. See, the image. Chemical Engg is newly addded.
But i dont know to reset or delete existing combo box contents. I know that the solution is a piece of code that makes the combo box null. It has to be placed on the top of combo box generation code. So, that it ll reset every time before generating new elements.
My question is how to make that combo box null in the starting point.(I dont know what exact term is "null" or "reset", i new to DOM elements).
Here my Code.
The HTML ELEMENT:
<select id="departmentField" >//Both using same data source.
<select id="searchDepartments">
The Script:
Its DWR Call... I think the problem comes below the grid.
EmployeeManagement.getDeptList(function(deptRecords) {
$("#depts").clearGridData(true);
$("#depts").jqGrid('addRowData', "deptID", deptRecords);
var deptSearchSelect = document.getElementById('searchDepartments');
var searchOptions = null;
searchOptions = document.createElement('option');
searchOptions.value = 0;
searchOptions.innerHTML = "ALL";
deptSearchSelect.appendChild(searchOptions);
var depFieldSelect = document.getElementById('departmentField');
var deptFieldOpts = null;
deptFieldOpts = document.createElement('option');
deptFieldOpts.value = 0;
deptFieldOpts.innerHTML = "";
depFieldSelect.appendChild(deptFieldOpts);
for(i = 0; i<deptRecords.length; i++) {
var dept = deptRecords[i];
searchOptions = document.createElement('option');
searchOptions.value = dept.deptID;
searchOptions.innerHTML = dept.deptName;
deptSearchSelect.appendChild(searchOptions);
deptFieldOpts = document.createElement('option');
deptFieldOpts.value = dept.deptID;
deptFieldOpts.innerHTML = dept.deptName;
depFieldSelect.appendChild(deptFieldOpts);
}
deptSearchSelect.selectedIndex = "ALL";
deptSearchSelect.selectedIndex = "";
//var respDiv = document.getElementById("respCheck");
});
How shall i reset?
Any suggestions would be more appreciative
Thanks in advance!!!
Try deleting each element in the select:
while(deptSearchSelect.hasChildNodes()) {
deptSearchSelect.removeChild(deptSearchSelect.firstChild);
}
while(depFieldSelect.hasChildNodes()) {
depFieldSelect.removeChild(depFieldSelect.firstChild);
}
Are you also not able to set the select box properly?

How do I access the "displayed" text of a select box option from the DOM?

Given the following HTML:
<select name="my_dropdown" id="my_dropdown">
<option value="1">displayed text 1</option>
</select>
How do I grab the string "displayed text 1" using Javascript/the DOM?
var sel = document.getElementById("my_dropdown");
//get the selected option
var selectedText = sel.options[sel.selectedIndex].text;
//or get the first option
var optionText = sel.options[0].text;
//or get the option with value="1"
for(var i=0; i<sel.options.length; i++){
if(sel.options[i].value == "1"){
var valueIsOneText = sel.options[i].text;
}
}
var mySelect = document.forms["my_form"].my_dropdown;
// or if you select has a id
var mySelect = document.getElementById("my_dropdown");
var text = mySelect.options[mySelect.selectedIndex].text;
Assuming you want the selected option's text:
var select = document.getElementById('my_dropdown');
for(var i = 0; i < select.options.length; i++) {
if(select.options[i].selected) {
break;
}
}
var selectText = select.options[i].text;
In Prototype:
var selectText = $$('#my_dropdown option[selected]')[0].text;
Edit: And jQuery for completeness' sake (assuming jQuery's CSS selector support is roughly equivalent to that of Prototype's):
var selectText = $('#my_dropdown option[selected]').get(0).text;
The displayed text is a child node of the option node. You can use:
myOptionNode.childNodes[0];
to access it, assuming the text node is the only thing inside the option (and not other tags).
EDIT: Oh yeah, as others mentioned, I completely forgot about:
myOptionNode.text;
Assuming you modified your code a bit to have an id / class on the and were using jQuery you could have something like the following. It will pop up an alert for each option with the text of the option. You probably won't want to alert for all the text, but it illustrates how to get at the text in the first place:
$('select#id option').each(function() {
alert($(this).text());
});
If you use a class instead of an id, then you'd just have to change the 'select#id' to 'select.class'. If you didn't want to add a class/id there are other ways to get at the select.
I leave figuring those ways out if you want to go that route as an activity for the reader.
If you were using Prototype, you could get at it like this:
$$('#my_dropdown option[value=1]').each( function(elem){
alert(elem.text);
});
The above is using a CSS selector that says find all option tags with value="1" that are inside the element that has id="my_dropdown".

Categories

Resources