appending the items into the combo box - javascript

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

Related

Dynamically Add Select Options with 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.

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]

Create Select Tag from Split String

How do I split this string:
waterfowl||tvs||guitar||pillow||mouse
...by ||?
Then, I'd like to create a select list like this:
<select name="options" id="options">
<option value="waterfowl">waterfowl</option>
<option value="tvs">tvs</option>
<option value="guitar">guitar</option>
<option value="pillow">pillow</option>
<option value="mouse">mouse</option>
</select>
var options = 'waterfowl||tvs||guitar||pillow||mouse';
$( '#someDiv' ).html( '<select name="options" id="options">'
+ options.replace(/(\w+)\|*/g, '<option value="$1">$1</option>')
+ '</select>' );
// Turns a string in to a combo box based on:
// #d Delimiter to split the string up by
// #so Select box attributes (adding name="foo" means passing {name:'foo'})
// Result: jQuery object of the new select element, populated with the items
// from the string
String.prototype.toSelect = function(d,so){
so = so || {};
var s = $('<select/>',so),
items = this.split(d);
for (var i = 0; i < items.length; i++){
$('<option/>').val(items[i]).text(items[i]).appendTo(s);
}
return s;
}
// an example
// Append the following string to the body of the document
// after it's been converted in to a <Select> element
$('body').append("waterfowl||tvs||guitar||pillow||mouse".toSelect('||',{
name: 'select',
id: 'select'
}));
Version with a bit more flexibility (and jQuery abilities): http://jsfiddle.net/j6DjR/
Preamble:
I used a <select> element with id and name attributes of
"assorted". "options" is a terrible id/name for a form element.
Read here for more: http://www.fortybelow.ca/hosted/comp-lang-javascript/faq/names/
Code:
No mess, no fuss.
(commonElements.testing is the form containing the <select> element)
var commonElements =
{
"testing": document.getElementById("testing"),
"assorted": document.getElementById("assorted")
},
options = "waterfowl||tvs||guitar||pillow||mouse";
function addOptions (optionList)
{
var i = 0,
limit = optionList.length,
parent = commonElements.assorted,
option;
for (i;i<limit;i++)
{
option = document.createElement(
"option"
);
option.text = optionList[i];
option.value = optionList[i];
parent.add(option, null);
}
}
function createOptions (toSplit)
{
var optionList = toSplit.split("||");
addOptions(optionList);
}
createOptions(options);
Working Link (with full code):
http://jsbin.com/ucajep
Try the following:
var input = 'waterfowl||tvs||guitar||pillow||mouse';
var split = input.split('||');
var select = $('<select name="options" id="options"></select>');
$.each(split, function(index, value) {
var option = $('<option></option>');
option.attr('value', value);
option.text(value);
select.append(option);
});
$('#idOfContainer').empty().append(select);
Your problem is simple:
Split string, using || as separator.
Loop over the splitted string.
Create a new option element
Set its value and text to the current item
Add the element to containing select element
Here's a simple implementation of it (without using jQuery). I use Array.prototype.forEach and element.textContent (the former being ES5 and latter being non-IE), but it should bring the point across (and they're not hard to shim).
function makeSelect( options, separator ) {
var select = document.createElement( 'select' ),
optionElem;
options.split( separator || '||' ).forEach(function( item ) {
optionElem = document.createElement( 'option' );
optionElem.value =
optionElem.textContent =
item;
select.appendChild( optionElem );
});
return select;
}
var selectElem = makeSelect( 'waterfowl||tvs||guitar||pillow||mouse' );
You can then manipulate selectElem just like you'd manipulate any other DOM element.
You can split the string into an array, then iterate through the array building an HTML string that you can then append to the DOM:
var str = 'waterfowl||tvs||guitar||pillow||mouse',//the string to be split
arr = str.split('||'),//the split string, each split stored in an index of an array
out = '';//our output buffer variable
//iterate through each array index
for (var index; index < arr.length; i++) {
//add this index to the output buffer
out += '<option value="' + arr[index] + '">' + arr[index] + '</option>';
}
//add the HTML we've built to the DOM, you can also use `.append(<code>)` instead of `.html(<code>)` but if you are using an ID for your select element then you ant to make sure and replace the HTML
$('#container-element').html('<select name="options" id="options">' + out + '</select>');
Here's a jsfiddle to demonstrate: http://jsfiddle.net/jasper/eb5Dj/

Converting a textbox into any other html element

<form name="txt" method="post">
<input type="text" name="select" id="select" onclick="return selectbox();">
</form>
Now through js or html can I change my textbox into a select or a list box. Is it possible by any way.
//js code
function selectbox()
{
var select=document.getElementById('select');
select.innerHTML="<select><option>1</option><option>2</option></select>";
}
Something like this should happen. In the place of the textbox the below code should appear
//new textbox
<select><option>1</option><option>2</option></select>
Yes, for example:
var select = document.createElement("select");
select.innerHTML = "<option value='1'>One</option>" +
"<option value='2'>Two</option>" +
"<option value='3'>Three</option>";
select.id = "select";
select.name = "select";
select.onclick = function(){return selectbox()};
var currentSelect = document.getElementById("select");
currentSelect.parentNode.replaceChild(select, currentSelect);
select.focus(); //Focus on the element
This code snippet creates a <select> element, and adds new options to it through .innerHTML. Then, the attributes are set. Finally. the script selects the current element with id="select" from the HTML document, and replaces the element by the newly created element.
Be more specific about what and how. You can try following
function selectbox(Sender){
var select = document.createElement('select');
//UPDATE
for(var i=1; i<=2; i++)
select.options[select.options.length] = new Option(i, i);
Sender.parentNode.appendChild(select);
Sender.parentNode.removeChild(Sender);
}

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