Dynamically Add Select Options with Javascript - javascript

So I've been working on trying to populate a select tag options with JavaScript. I can't seem to figure out why my function isn't working any help would be greatly appreciated.
My HTML code:
<select name="options" id="options" style="width: 100px;" onchange="chooseOption(this);">
</select>
And my JavaScript function:
function chooseOption(){
var choices = {"Gym","Pool","Sports"};
var myChoice = "";
for(i=0; i<=choices.length; i++){
myChoice += "<option value='"+choices[i]+"'>"+choices[i]+"</option>";
document.getElementById("options").innerHTML = myChoice;
}
}
Thanks again

I would go with something like.
Is not really tested but am pretty sure is more reliable.
var option = document.createElement("option");
for(i=0; i<=choices.length; i++){
option.text = choices[i];
option.value = choices[i];
document.getElementById("options").appendChild = myChoice;
}

You're attempting to create an object instead of an array here:
var choices = {"Gym","Pool","Sports"}; // change {} to [] to create an array
Curly braces - {} are used to denote that you are creating an object.
Brackets - [] are used to denote an array.
Try populating your select element as it's being created with something like this:
<select name="options" id="options" style="width: 100px;">
<script>
var choices = ["Gym","Pool","Sports"];
var myChoice = "";
for(var i=0; i < choices.length; i++) {
myChoice += "<option value='"+choices[i]+"'>"+choices[i]+"</option>";
document.getElementById("options").innerHTML = myChoice;
}
</script>
</select>

Firstly, you have a huge error.
You don't use { and } in javascript to create arrays.
Use:
var choices = ["Gym","Pool","Sports"];
Here is your final code:
<script>
function chooseOption() {
var choices = ["Gym", "Pool", "Sports"];
var myChoice = "";
for (i = 0; i <= choices.length; i++) {
myChoice += "<option value='" + choices[i] + "'>" + choices[i] + "</option>";
document.getElementById("options").innerHTML = myChoice;
}
}
</script>
<select name="options" id="options" style="width: 100px;" onclick="javascript:chooseOption(this);">
</select>
Update
If you want it to work on JSFiddle firstly you need to make your function globally available because JSFiddle runs it at domready. To make it globally available just write it like this: window.choseOption = function() { /* code here */ };.
You should read a bit on DOM events. The change event on that select won't fire up until you have selected something. And since you have nothing to select the event will not fire.
You can run the function at onclick or just run it when the DOM is ready.
I have updated your fiddle.

Related

Building HTML Selection field and selecting option with JavaScript Array

I have some JavaScript Arrays that are used to generate HTML selection fileds and then to also make the option a user has selected as the selected opton in the generated Selection list.
I have a working example for a basic JavaScript array. I need help with a more complex JS array though.
function buildFormSelection(optionArray, selectedOption){
var optionsHtml = '';
for(var i = 0; i < optionArray.length; i++){
optionsHtml += "<option value='" + optionArray[i] + "' "
+ (selectedOption == optionArray[i] ? "selected='selected'" : "")
+ ">" + optionArray[i] + "</option>";
}
return optionsHtml;
};
var typesArray = ['Other', 'SugarCRM', 'Magento', 'Design'];
console.log(buildFormSelection(typesArray, 'SugarCRM'));
This generates this HTML output...
<option value='Other'>Other</option>
<option value='SugarCRM' selected='selected'>SugarCRM</option>
<option value='Magento'>Magento</option>
<option value='Design'>Design</option>
Here is a JSFiddle to show it working. http://jsfiddle.net/jasondavis/4twd8oz1/
My issue is I now need to have the same functionality on a more complex array like this one below. It has an ID and a Name Value...
var milestonesArray = [
['1','Milestone 1'],
['2','milestone 2'],
]
Using similar code as my function above, I need to pull in a user's selected value from a database for example if they have saved the value of 2 then it should select selection option of 2 and show the text milestone 2 from a selection that looks like this...
<option value='1'>milestone 1</option>
<option value='2' selected='selected'>milestone 2</option>
I am not sure how to properly build a JavaScript array that can handle a key and value like this and make my function work with the milestone array.
Any help please?
What you need to do just add another array index to your function like so:
function buildFormSelection(optionArray, selectedOption){
var optionsHtml = '';
for(var i = 0; i < optionArray.length; i++){
optionsHtml += "<option value='" + optionArray[i][0] + "' "
+ (selectedOption == optionArray[i][0] ? "selected='selected'" : "")
+ ">" + optionArray[i][1] + "</option>";
}
return optionsHtml;
};
Where optionArray[i][0] is the value and optionArray[i][1] is the text.
JSFiddle
Answers with lots of code is usually frowned on but this is a trivial solution as #imtheman pointed out in his answer. But not everything needs to be so concise.
function makeOptionElement(value, title, selected) {
var option = document.createElement('option');
option.value = value;
if (selected) {
option.setAttribute('selected', 'selected');
}
option.innerHTML = title;
return option;
}
function dataToOptions(data, selectedIndex) {
var selectList = document.createElement('select');
data.forEach(function(item, index) {
var isSelected = (index === selectedIndex);
var option = makeOptionElement(item[0], item[1], isSelected);
selectList.appendChild(option);
});
return selectList;
}
Essentially, each time you call the array with your variables to be printed, you are calling the contents of the array in the position specified between the [ ]. It may be another array. That you can access as you would any other array. So, it would be:external_array[extrenal_array_index][internal_array_index]

get value in javascript from select tag

I am using a javascript function to get the id from a particular <select></select>.
<select name="no" id="dropdownlist" class="defaultvalue" style="width: 100%;">
<option value="">Select Option</option>
</select>
But the problem is I have 8 <select></select> for dropwdown and i want to get the value of these in the javascript like:
var list = document.getElementById('dropdownlist');
But this is only possible through using getElementByClass but this is not working for me. Any help would be appreciated.
Due you tagged your question with jquery I suggest you using it:
$('#dropdownlist').val();
UPDATE: But if you have 8 selects - just use same class for them and you can use next code:
$('.className').each(function(i,el){
console.log($(this).val());
})
There is no getElementByClass, it's getElementsByClassName, but you might as well use querySelectorAll, which has better support
var list = [];
var elems = document.querySelectorAll('.defaultvalue');
for (var i=0; i<elems.length; i++) {
list.push( elems[i].value );
}
FIDDLE
in jQuery you can do
var list = $.map($('.defaultvalue'), function(el) { return el.value});
FIDDLE
And ID's are unique, they can not be used for more than one element in the same document
If you want to go with pure javascript with multi select tag, then use below code
Update
function getAllValue(){
var allSelectTags = document.getElementsByClassName("defaultvalue");
var selVal = [];
for(var i=0; i<allSelectTags.length; i++){
var value = allSelectTags[i].options[allSelectTags[i].selectedIndex].value;
selVal.push(value);
}
var result = "";
for(var j=0; j<selVal.length; j++){
result += selVal[j] + "<br />";
}
document.getElementById("result").innerHTML = result;
}
DEMO

drop down list items taken from the java script

<select id="myList" onchange="favBrowser()">
<option> var x</option>
<option> var y</option>
</select>
<script>
var x="google"; var y="firefox";
</script>
my question is , how to take the option's values from javascript
i think he ment he want to fill the options by Script
this can be done by
<select id="myDropdown">
</select>
<script type="text/javascript">
function fillDropDown() {
var ddl = document.getElementById('myDropdown');
for (var i = 1; i < 50; i++) {
var myNewOption = new Option();
myNewOption.value = i;
myNewOption.text = "my " + i.toString() + " option...";
ddl.options.add(myNewOption);
}
}
fillDropDown();
</script>
Cheers.
You can get it by writing
function favBrowser(){
var sel = document.getElementById("myList");
var value =sel.options[sel.selectedIndex].value;
window.alert(value);
}
You need to supply more information about what it is you really want to do. If what you want is to take the selected value, then take a look at this question
Get selected value in dropdown list using JavaScript?

appending the items into the combo box

I need to add the item in a combo box for a particular number of times.This is my code.
for(i=0;i<3;i++)
{
othercompaniesli.innerHTML= '<select onchange="document.location.href = this.options[this.selectedIndex].value;"><option VALUE="http://www.google.com">'+fStr1[0]+'</option> </select>';
}
Here I want to add the fStr1 string 3 times.But it adds only one time.That is the for loop is working but only item value is not appending.Only last value is added in the combo box. Can anyone help me how to append the items into combo box.
var tmpStr = '<select onchange="document.location.href = this.options[this.selectedIndex].value;">';
for(i=0;i<3;i++)
{
tmpStr+= '<option VALUE="http://www.google.com">'+fStr1[0]+'</option> ';
}
tmpStr = '</select>';
othercompaniesli.innerHTML = tmpStr;
try othercompaniesli.innerHTML +=.
Since you are using equal to =, it is re-assigning to the same element
Use append()
$('#othercompaniesli').append('<select onchange="document.location.href = this.options[this.selectedIndex].value;"><option VALUE="http://www.google.com">'+fStr1[0]+'</option> </select>');
Note that your select and option elements are repeating, you need to change it accordingly.
Place select tag out of loop
var selectTag = '<select onchange="document.location.href = this.options[this.selectedIndex].value;">';
for(i=0;i<3;i++) {
selectTag += '<option VALUE="http://www.google.com">'+fStr1[0]+'</option>';
}
selectTag +="</select>"
othercompaniesli.innerHTML = selectTag;
What you are doing is the inside the loop you are ending your select tag , so every element will have it own select opening and closing tag. and you are just updating your innerHTML with the newer element thats why its getting the last element.
var openingTag= '<select onchange="document.location.href = this.options[this.selectedIndex].value;">';
for(i=0;i<3;i++)
{
openingTag+= '<option VALUE="http://www.google.com">'+fStr1[0]+'</option> ';
}
openingTag= '</select>';
othercompaniesli.innerHTML = openingTag;
var select= $('mySelect');
var opt = new Option("OptionTitle", "123");
select.selectedIndex = InsertNewOption(opt, select[0]);
function InsertNewOption(opt, element)
{
var len = element.options.length;
element.options[optsLen] = opt;
return len;
}

Best way to create a dynamic Select (Dropdown) list?

I'm using jQuery and jqGrid.
I'm trying to populate a select list dynamically, one for each row and I need to add a click event to it. When the select list is being populated I grab the index of the item I want selected, and then after all items are add I'm trying to set the selected item.
I've tried
$("#taskList")[0].selectedIndex = taskIndex;
$("#taskList").selectOptions(taskIndex, true);
$("#taskList").val(1); //Tried to see if I could select any index and no luck.
$("#taskList option[value=" + taskIndex + "]").attr("selected", true);
So this means I'm probably populating the list incorrectly...
var taskList = document.createElement("select");
var taskIndex = 0;
for (var i = 0; i < result.TaskTypes.length; i++) {
$(taskList).addOption(result.TaskTypes[i].TaskId, result.TaskTypes[i].TaskName);
if (result.TaskTypes[i].TaskName == rowData.TaskType)
taskIndex = i;
}
Is there a better way?
I tried this but I couldn't add the click event to it. The proper item was selected though.
var taskList = "<select name='taskList' Enabled='true'>";
for (var i = 0; i < result.TaskTypes.length; i++) {
if (result.TaskTypes[i].TaskName == rowData.TaskType)
taskList += "<option selected> " + result.TaskTypes[i].TaskName + "</option>";
else
taskList += "<option>" + result.TaskTypes[i].TaskName + "</option>";
}
taskList += "</select>";
The way I would have done it, is in your first example - instead of using the jQuery API for addOption, use the DOM API, like this:
var option = document.createElement("option");
option.innerHTML = result.TaskTypes[i].TaskName;
option.value = result.TaskTypes[i].TaskId;
option.onclick = myClickHandler;
taskList.add(option, null);
Then after the loop you can just use:
taskList.selectedIndex = taskIndex;
to have the select list positioned to your required default selection.
I haven't used jQuery extensively, but I think its a good idea not to neglect the DOM API - its often not as convenient as the shortcuts that jQuery and other libraries offer, but these extend DOM capabilities and should not come instead of the DOM.
You can set the selected index like this:
$("#taskList").selectedIndex = taskIndex;
Falling under the "better way" category, JQuery lets you use an each loop instead of creating the for loops manually.
jQuery.each(result.TaskTypes, function(i, val) {
$("#" + i).append(document.createTextNode(" - " + val));
});
Got it- a good solid 8 hours later.
var taskList = "<select name='taskList' Enabled='true' onClick='$(\"#hoursBx\").valid()' >";
for (var i = 0; i < result.TaskTypes.length; i++) {
if (result.TaskTypes[i].TaskName == rowData.TaskType)
taskList += "<option selected> " + result.TaskTypes[i].TaskName + "</option>";
else
taskList += "<option>" + result.TaskTypes[i].TaskName + "</option>";
}
taskList += "</select>";
I'm using jQuery's Validator to verify the value in the $("#hoursBx") (a text box in the current row).
Adding the onClick works.

Categories