how to append option to a select - javascript

I have a variable which contains a number. I'd like to append an option with the numeric value in each based on whatever the variable number is ( ie: if total equals 10, then I need to add 10 options to the select with each option containing the next numeric row value, so 1, 2, 3, 4...etc. I start off with one hard coded option, and then I need to add options dynamically for every case. I've tried a multitude of scripts but I"m getting " cannot use in operator to search for length.
https://jsfiddle.net/v1yyhfm8/
HTML
<select id="main">
<option selected>1</option>
</select>
I tried:
var total = dataSource.total();
for (var i = 1; 1 <= total; i++) {
var added = document.createElement('option');
var test = $('#main');
added.value = i;
added.innerHTML = i;
test.append(added);
}
and
var total = dataSource.total();
$.each(total, function (i, item) {
$('#main').append($('<option>', {
value: item.total,
text: item.text
}));
});

In your code, the for loop condition would be true always which leads to an infinite loop so change it to i <= total.
var total = dataSource.total();
for (var i = 1; i <= total; i++) {
var added = document.createElement('option');
var select1 = $('#main');
added.value = i;
added.innerHTML = i;
select1.append(added);
}
var total = 10;
for (var i = 1; i <= total; i++) {
var added = document.createElement('option');
var select1 = $('#main');
added.value = i;
added.innerHTML = i;
select1.append(added);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="main">
<option selected>1</option>
</select>

Html part :
<select id="main">
</select>
Jquery Part:
var opt = ' <option selected>1</option>';
for(var i = 2; i<= 10; i++){
opt += ' <option>' + i + '</option>';
}
$("#main").append(opt);
Jsfiddle link : https://jsfiddle.net/v1yyhfm8/

Related

2nd dropdown options determined by 1st dropdown [duplicate]

I need to change the contents of dropdown B based on the selection in dropdown A using javascript. There are no db queries involved--I know beforehand what the contents of B should be given the choice in A. I have found some examples using AJAX, but since there is no db query involved that's not necessary. Can anyone point me to some example code for how to do this?
function configureDropDownLists(ddl1, ddl2) {
var colours = ['Black', 'White', 'Blue'];
var shapes = ['Square', 'Circle', 'Triangle'];
var names = ['John', 'David', 'Sarah'];
switch (ddl1.value) {
case 'Colours':
ddl2.options.length = 0;
for (i = 0; i < colours.length; i++) {
createOption(ddl2, colours[i], colours[i]);
}
break;
case 'Shapes':
ddl2.options.length = 0;
for (i = 0; i < shapes.length; i++) {
createOption(ddl2, shapes[i], shapes[i]);
}
break;
case 'Names':
ddl2.options.length = 0;
for (i = 0; i < names.length; i++) {
createOption(ddl2, names[i], names[i]);
}
break;
default:
ddl2.options.length = 0;
break;
}
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
<select id="ddl" onchange="configureDropDownLists(this,document.getElementById('ddl2'))">
<option value=""></option>
<option value="Colours">Colours</option>
<option value="Shapes">Shapes</option>
<option value="Names">Names</option>
</select>
<select id="ddl2">
</select>
Setup mine within a closure and with straight JavaScript, explanation provided in comments
(function() {
//setup an object fully of arrays
//alternativly it could be something like
//{"yes":[{value:sweet, text:Sweet}.....]}
//so you could set the label of the option tag something different than the name
var bOptions = {
"yes": ["sweet", "wohoo", "yay"],
"no": ["you suck!", "common son"]
};
var A = document.getElementById('A');
var B = document.getElementById('B');
//on change is a good event for this because you are guarenteed the value is different
A.onchange = function() {
//clear out B
B.length = 0;
//get the selected value from A
var _val = this.options[this.selectedIndex].value;
//loop through bOption at the selected value
for (var i in bOptions[_val]) {
//create option tag
var op = document.createElement('option');
//set its value
op.value = bOptions[_val][i];
//set the display label
op.text = bOptions[_val][i];
//append it to B
B.appendChild(op);
}
};
//fire this to update B on load
A.onchange();
})();
<select id='A' name='A'>
<option value='yes' selected='selected'>yes
<option value='no'> no
</select>
<select id='B' name='B'>
</select>
Could you please have a look at: http://jsfiddle.net/4Zw3M/1/.
Basically, the data is stored in an Array and the options are added accordingly. I think the code says more than a thousand words.
var data = [ // The data
['ten', [
'eleven','twelve'
]],
['twenty', [
'twentyone', 'twentytwo'
]]
];
$a = $('#a'); // The dropdowns
$b = $('#b');
for(var i = 0; i < data.length; i++) {
var first = data[i][0];
$a.append($("<option>"). // Add options
attr("value",first).
data("sel", i).
text(first));
}
$a.change(function() {
var index = $(this).children('option:selected').data('sel');
var second = data[index][1]; // The second-choice data
$b.html(''); // Clear existing options in second dropdown
for(var j = 0; j < second.length; j++) {
$b.append($("<option>"). // Add options
attr("value",second[j]).
data("sel", j).
text(second[j]));
}
}).change(); // Trigger once to add options at load of first choice

Add alphabets dynamically as html row increments

How to ensure i have a dynamic increment of Alphabets in a new cell on left side, next to each cell in a row which is dynamically created based on the option chosen in Select. This newly generated alphabet will be considered as bullet points/serial number for that particular row's text box.
jsfiddle
js code
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
html
<select id="Number_of_position">
</select> <table id="Positions_names">
</table>
This is essentially a base26 question, you can search for an implementation of this in javascript pretty easily - How to create a function that converts a Number to a Bijective Hexavigesimal?
alpha = "abcdefghijklmnopqrstuvwxyz";
function hex(a) {
// First figure out how many digits there are.
a += 1; // This line is funky
var c = 0;
var x = 1;
while (a >= x) {
c++;
a -= x;
x *= 26;
}
// Now you can do normal base conversion.
var s = "";
for (var i = 0; i < c; i++) {
s = alpha.charAt(a % 26) + s;
a = Math.floor(a/26);
}
return s;
}
So you can do
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td>" + hex(i) + "</td><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
Heres the example http://jsfiddle.net/v2ksyy7L/6/
And if you want it to be uppercase just do
hex(i).toUpperCase();
Also - this will work up to any number of rows that javascript can handle
if i have understood you correctly, that's maybe what you want:
http://jsfiddle.net/v2ksyy7L/3/
I have added an array for the alphabet:
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
and then added the output to your "render" loop:
rows += "<tr><td>" + alphabet[i] + " <input type='text'></td></tr>";

Add item to dropdown list in HTML using JavaScript

I have this JavaScript+HTML to populate a dropdown menu but it is not working, am i doing anything wrong? Note I want the drop down menu to be filled on page Load
<!DOCTYPE html>
<html>
<head>
<script>
function addList(){
var select = document.getElementById("year");
for(var i = 2011; i >= 1900; --i) {
var option = document.createElement('option');
option.text = option.value = i;
select.add(option, 0);
}
}
</script>
</head>
<body>
<select id="year" name="year"></select>
</body>
</html>
Since your script is in <head>, you need to wrap it in window.onload:
window.onload = function () {
var select = document.getElementById("year");
for(var i = 2011; i >= 1900; --i) {
var option = document.createElement('option');
option.text = option.value = i;
select.add(option, 0);
}
};
You can also do it in this way
<body onload="addList()">
For higher performance, I recommend this:
var select = document.getElementById("year");
var options = [];
var option = document.createElement('option');
//for (var i = 2011; i >= 1900; --i)
for (var i = 1900; i < 2012; ++i)
{
//var data = '<option value="' + escapeHTML(i) +'">" + escapeHTML(i) + "</option>';
option.text = option.value = i;
options.push(option.outerHTML);
}
select.insertAdjacentHTML('beforeEnd', options.join('\n'));
This avoids a redraw after each appendChild, which speeds up the process considerably, especially for a larger number of options.
Optional for generating the string by hand:
function escapeHTML(str)
{
var div = document.createElement('div');
var text = document.createTextNode(str);
div.appendChild(text);
return div.innerHTML;
}
However, I would not use these kind of methods at all.
It seems crude. You best do this with a documentFragment:
var docfrag = document.createDocumentFragment();
for (var i = 1900; i < 2012; ++i)
{
docfrag.appendChild(new Option(i, i));
}
var select = document.getElementById("year");
select.appendChild(docfrag);
Try this
<script type="text/javascript">
function AddItem()
{
// Create an Option object
var opt = document.createElement("option");
// Assign text and value to Option object
opt.text = "New Value";
opt.value = "New Value";
// Add an Option object to Drop Down List Box
document.getElementById('<%=DropDownList.ClientID%>').options.add(opt);
}
<script />
The Value will append to the drop down list.
Try to use appendChild method:
select.appendChild(option);
i think you have only defined the function. you are not triggering it anywhere.
please do
window.onload = addList();
or trigger it on some other event
after its definition
see this fiddle

How to Split a dynamic variable into drop down box ( variable seperated by comma)

var device_name = sreeni , murtuza , deepu , bharath , ...... n th number
i need to split this Variable based on the comma and put it in a drop down box.
example:
sreeni
murtuza
deepu
bhatah
Please provide a solution using through Javascript or Jquery
With plain JS,
var device_name = "sreeni , murtuza , deepu , bharath"
var list = device_name.split(/\s*,\s*/);
var dd = document.getElementById("myDropDown");
for(var i = 0; i< list.length; i++){
dd.innerHTML += '<option value="'+list[i]+'">'+list[i]+'</option>';
}
JSFiddle
More Hacky way,
document
.getElementById("myDropDown2")
.innerHTML = device_name
.replace(
/\w+/g,
function(m){
return '<option value="'+m+'">'+m+'</option>'
}
)
.replace(/\s*,\s*/g,'');
var strings = "sreeni,murtuza,deepu,bhatah";
var splitStrings = strings.split();
var selectObj = document.createElement("option");
for (var i in splitStrings) {
selectObj.options[selectObj.options.length] = new Option(splitStrings[i], splitStrings[i]);
}
document.getElementById("idOfElementToContainDropdown").appendChild(selectObj);
var names = device_name.split(",");
var combo = document.getElementById("comboId");
//for i = 1 to length of names list {
var item = document.createElement("OPTION");
item.text=names[i];
combo.options.add(item);
}
Hope this is helpful for you.
var myListOfWords = "apple,orange,bananna,cherries";
var list = myListOfWords.split(",");
var dd = document.getElementById("myDropDown");
for(var i = 0; i< list.length; i++){
var objOption = document.createElement("option");
objOption.text = list[i]
dd.add(objOption) ;
}
//and somewhere in your html
<select id="myDropDown"/>
Here's the working example: dynamic drop down fiddle
With jQuery:
$('#myDropDown').empty();
$.each(device_name.split(","), function(iIndex, sElement) {
if ($.trim(sElement).length > 0) {
$('#myDropDown').append('<option>' + $.trim(sElement) + '</option>');
}
});
Also see this example.

How to show <Select > in sorted order

How can I sort the <option> elements of a <select> tag using JavaScript?
Here is the HTML I have:
<form action="example.asp">
<div>
<select size="3">
<option value="op2" >Option 2</option>
<option value="op1">Option 1</option>
<option value="op4">Option 4</option>
<option value="op3">Option 3</option>
</select>
</div>
</form>
If the value is different than the text, use the following function to sort both of them. This is just an updated version of above solution and will keep both the name and associated value.
<script language="JavaScript" type="text/javascript">
function sortList()
{
var lb = document.getElementById('mylist');
arrTexts = new Array();
arrValues = new Array();
arrOldTexts = new Array();
for(i=0; i<lb.length; i++)
{
arrTexts[i] = lb.options[i].text;
arrValues[i] = lb.options[i].value;
arrOldTexts[i] = lb.options[i].text;
}
arrTexts.sort();
for(i=0; i<lb.length; i++)
{
lb.options[i].text = arrTexts[i];
for(j=0; j<lb.length; j++)
{
if (arrTexts[i] == arrOldTexts[j])
{
lb.options[i].value = arrValues[j];
j = lb.length;
}
}
}
}
</script>
<script language="JavaScript" type="text/javascript">
function sortlist() {
var lb = document.getElementById('mylist');
arrTexts = new Array();
for(i=0; i<lb.length; i++) {
arrTexts[i] = lb.options[i].text;
}
arrTexts.sort();
for(i=0; i<lb.length; i++) {
lb.options[i].text = arrTexts[i];
lb.options[i].value = arrTexts[i];
}
}
</script>
<form action="#">
<select name=mylist id=mylist size=5>
<option value="Anton">Anton
<option value="Mike">Mike
<option value="Peter">Peter
<option value="Bill">Bill
<option value="Carl">Carl
</select>
<br>
sort
</form>
You should think about it on the pre html-creation level. If you are generating them from some kind of list or by dynamic page mechanism then sort them before you generate your option elements - thats the clearest way ;)
A simpler solution, building on Yasir Al-Agl's answer:
function sortList()
{
var lb = document.getElementById('mylist');
arr = new Array();
for(i = 0; i < lb.length; i++) {
arr[i] = lb.options[i];
}
arr.sort(function(a,b) {
return (a.text > b.text)? 1 : ((a.text < b.text)? -1 : 0);
}); // or use localeCompare() if you prefer
for(i = 0; i < lb.length; i++) {
lb.options[i] = arr[i];
}
}
In short, you need only one Array, the elements of which are simply references to the original "options" Objects. The sort() function also has the freedom to choose which option property to sort on (ie, the text property, the value property, etc).
Don't forget, however, that the "selectedIndex" property of the "select" control may no longer be correct after the sort.
This function works as in the last answer, but also keeps the selection of item
// Sorts all entries of a select item (= dropdown) by their visible name, keeping the internal values and the selection
function sortSelectEntries(selItem) {
let formerSel = selItem.value;
let count = selItem.length;
let options = new Array();
for (var i = 0; i < count; i++)
options[i] = selItem.options[i];
options.sort((e1, e2) => e1.text > e2.text ? 1 : (e1.text < e2.text ? -1 : 0));
for (i = 0; i < count; i++)
selItem.options[i] = options[i];
selItem.value = formerSel; // restore selection
}

Categories

Resources