Parse html list with javascript then output drop down - javascript

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

Related

how to get all selected option select2

I have many select2 in one page so I want to get all selected option as a array
how it's possible?
i've tried this
console.log($("select").val());
but it just gives me the first selected option
I hope this will work :
var select = $("select");
var valArray = [];
select.each(function(index){
valArray.push($( this ).val());
});
console.log(valArray);

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);
}

Create and Copy a select box with jquery

We want to make a new select box and copy its options from another select box when an event happens. We use below code:
//Create a new select box and add it to a div
$('#content').append("<select id='destination'/>");
//Create copy source options
var $options = $("#source > option").clone();
//Append source option to destination
$("#destination").append($options);
http://jsfiddle.net/e8ctkkvL/1/
I have a page with lots of selects(each with lots of options), above code is slow ! Is there any way I can make above JS faster ?!
I'd rather copy the source and set a dynamic id since you may want to have multiple select boxes and different IDs, like below:
Demo#Fiddle
$(document).ready(function () {
var id = 1;
$("#btn").click(function () {
//Create a new select box
$('#content').append($("#source").clone(true).attr({id: "destination" + id}));
id++;
});
});
You should set a class instead of an ID and then append it to the last created select, for example:
$(document).ready(function () {
$("#btn").click(function () {
//Create a new select box
$('#content').append("<select class='destination'/>");
//Create copy source options
var $options = $("#source > option").clone();
//Append source option to destination
$(".destination").last().append($options);
});
});
Fiddle: http://jsfiddle.net/e8ctkkvL/3/

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

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>

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