Populating multiple drop-down menus with static values - javascript

This is a relatively straightforward task I'd like to accomplish without jquery or AJAX.
I have a couple javascript arrays A and B, and I have multiple rows in an HTML form that each contain two columns containing dropdowns which will each contain the contents of A and B. I'd like to populate every dropdown of a certain name with a predefined set of items. This can be done after the page has already loaded.
Any ideas as to what the javascript would look like? How can I address a slew of items named one thing?

This is the code for one of your arrays:
// String values; can be used as name, id, or innerHTML
var valsA = ['one','two','three'];
// Variable to store <option> object
var opt;
// Loop through vals and make an <option> for each one
for(var i=0;i<valsA.length;i++) {
// Create node
opt = document.createElement("OPTION");
// Set innerHTML, if you want
opt.innerHTML = valsA[i];
// Set the names to be all the same, if you want
opt.setAttribute("name","oneThing");
// Set unique ID, somehow, if you want
opt.id = "value"+i+valsA[i];
// Finally, append <option> to dropdown menu
document.getElementById('myDropdown').appendChild(opt);
}
Your HTML should have a <select id='myDropdown'></select> ready to go before this script is run. You can do the same process for the other array.
Also, keep in mind that names
are not necessarily unique
can be used to get groups of items
while IDs
should be unique
unfortunately your script will run if they're not, this can be a source of errors
should be used to get a single object
So, make sure each of your dropdowns has a unique ID so your script can find it correctly.

If your HTML lookes like this:
<body>
<select id="fillme" name="fillme"></select>
<select id="fillme" name="fillme"></select>
<select id="fillme" name="fillme"></select>
<select id="fillme" name="fillme"></select>
</body>
And you just want to fill in the values from multiple arrays:
var a = ['one','two','three'];
var b = ['four', 'five'];
You can concatenate the arrays and use getElementsByName (as long as the selects have ids matching the names too, IE needs that).
var values = a.concat(b);
var selects = document.getElementsByName('fillme');
var i = selects.length;
while (i--) {
var select = selects[i];
for (var j=0,length=values.length; j<length; j++) {
select.add(new Option(values[j]));
}
}​
JSBin Demo: http://jsbin.com/ehoni4/2

Related

Sending all items in a select element to a JavaScript array

I am currently using two select elements and utilizing js buttons to send options back and forth between elements. Users will move options from the left side to the right side and submit the page to make changes to their database. I am able to move elements back and forth with:
var array = $("#elementID option:selected").toArray();
without trouble.
I would like to be able to utilize this same method to send all Select Element options to an array regardless of whether or not they were selected.
I've tried
removing the option tag:
var array = $("#elementID").toArray();
using different operators within the option tag:
var array = $("#elementID option:all").toArray(); var array = $("#elementID option:unselected").toArray();
I am unable to find any documentation for further usage of the option tag outside of "selected"
Here is my full button:
$("#clearGroup").on("click", function(){
var allItems = $("#activeGroups option:selected").toArray();
console.log(allItems);
var allAvail = document.getElementById("availableGroups");
var allAct = document.getElementById("activeGroups");
allItems.forEach(function(item){
//remove Options from right side side
//activeGroups.remove(activeGroups.selectedIndex);
//Establish child option and add it to activeGroup Select Element
var opt = document.createElement('option');
opt.value = item.value;
opt.innerHTML = item.text;
allAvail.appendChild(opt);
allAct.removeChild(item);
})
Removing :selected worked as desired and allowed for all options in the select element to be successfully passed into the array. The line now looks like:
var allItems = $("#activeGroups option").toArray();

How to fix issue with appending optgroup to a select2 drop down?

I am trying to make a drop down using selct2 all in JQuery. So I have an ajax call that is sent from Java to my Jquery that has a list of parent and child elements and it is being held in a List as Strings. So for example:
WEB
-->Apache
-->Nginx
-->Random
DATABASE
-->Sql
-->NoSQL
COMPUTER SYSTEM
-->Windows File Share
I am looking for any way to fill a select2 dropdown by making a <optgroup> and having values inside of that group. I looked into making a HashMap or another way, but not sure how to go about it in JQuery. Please help. Below is the code I got so far but, it is only adding everything as a option, instead of surrounding it in optgroup.
Code:
$.each(result, function(i, obj) {
var div_data = "<option value=" + obj + ">"
+ obj + "</option>";
$(div_data).appendTo('#selectData2');
});
Here is a jsFiddle that assumes you're receiving a JavaScript object that is structured like my example:
// Example javascript object where the option group title is the key/index
// and the options for each are an array
var example_object = {
'Web': ['apache','nginx','random'],
'Database': ['sql','nosql'],
'Computer System': ['Windows','Other']
};
// The element you're appending options to
var select = $('select');
// Loop through each item in the object
$.each(example_object, function(category,items){
// Create an optgroup element with jQuery, the label is the category
var group = $('<optgroup>').attr({label: category});
// Loop through items in that category
$.each(items, function(index,item){
// Create an option element with jQuery, set the value and html
// Append to the group
$('<option>').attr({value: item}).html(item).appendTo(group);
})
// Now we have an optgroup containing all of the children items
// Append to select element
group.appendTo(select);
})
This isn't perfect but I hope it helps!

Dynamic id creation with Javascript

I am creating a table that changes size based on a javascript array. I am modeling reservations and when the page loads it loops through an array of reservation objects and creates a table to represent them. I have a checkbox created as the first element of each row as such:
checkboxCell.innerHTML = "<input type='checkbox'>";
I want to be able to know which row(or checkbox) I am clicking when they are pressed. Since these are being creating in one line, they would all have the same ID. So I either need a way to know where I am in the table or a way to create a different ID for each of these elements.
You can generate incremental ID's for your new elements within the loop which is creating the new HTML elements, e.g. assuming you're appending inputs to an element with an ID of parent-element:
function makeElements(){
var parent = document.getElementById('parent-element');
for (var i = 1; i < 11; i++) {
var newElement = document.createElement('input');
newElement.id = 'input-number-' + i;
newElement.type = "checkbox";
parent.appendChild(newElement);
}
}
As commented by connexo however you are probably better off using an existing library to take care of this sort of thing.

Javascript removing and rearranging array elements

I have this collection of images resources where that is stored in array, the user will select an image and then the selected image will be removed from the list(also from the array) and after that The array would be rearrange. How could I perform such task? (as much as possible I do not want to use an open source library)
Sounds like you need to look up splice() method. It allows you to add and remove one to many items within an array at any index.
here's reference for it.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/splice
your question lacks a code example but you can use Array.splice(index,number) whereas index is zero based and number is how many items to remove.
images.splice(selectedIndex,1);
Simply, you can create a temporary array where you store the initial array elements you need and reassign the value of your initial array to the temporary array.
function clean_array(my_array){
var no_need_value = 'value you want to remove'
var tmpArray = new Array()
for (var i = 0; i < my_array.length; i++)
if (my_array[i] != no_need_value)
tmpArray.push(my_array[i])
my_array = tmpeArray
}

Create an array from a string

I have a webpage where a user can select multiple items from a jquery list.
Based on the item(s) selected I need to add each item into the database.
When someone selects one item the value returned to my Javascript is similar to "4~2"
The value 4 would be used in my example for one column named "skill_id" in the database and the value 2 would be used for another column called "category_id" in the same row.
When someone selects two items it is comma-delimited and similar to "4~2,6~7" and so on if they select more than 2.
I'm thinking I need to do a for loop with an array or a jquery.each() function but not certain how the best way to approach this is.
What you're looking for is the split() method.
"4~2,6~7".split(',') // ['4~2', '6~7']
Here is one way you could extract the skill_id and category_id:
$.each("4~2,6~7".split(','), function(index, value) {
var nums = value.split("~");
var skill_id = nums[0];
var category_id = nums[1];
});

Categories

Resources