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

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!

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

SharePoint - Use JavaScript to get the list items after filter is applied

Consider I have a list called "test"
And it has 5 list items (say a, b, c, d, e)
Now that I apply filter manually on the list items for a particular field
Now the result is 3 list Items.
Now I want to read the fields of these 3 list items through JavaScript & do calculation on it.
I need to access the fields of the currently displayed (after filter is applied manually)
I do not want to filter it in Javascript. But I want to filter some field manually & then I want to read the displayed result. Can anyone help ?
The following jQuery will get all the values for a column for the rows that are displayed. It works on SharePoint 2010. I left the code very verbose and with debugging statements so it's easier to understand. Keep in mind that this code will not run in IE with the console closed unless you remove the console.log and debugger lines.
$(document).ready(function() {
var columnHeading = "Title";
var anchor = $("a").filter(function() {
return $(this).text() === columnHeading; //find the link that matches the text in the columnHeading variable
});
var th = anchor.closest("th"); //Get the parent table header
var columnIndex = th.index(); //Get the index of the table header in the row for use on other rows
var table = th.closest("table");
var i;
debugger;
table.find("tbody").first().find("tr").not(":first").each(function() { //Loop over every row in the table EXCEPT the first row because its the table header
i = $(this).find("td").eq(columnIndex); //find the td element at the index we determined earlier
console.log($(i).text()); //get the text in the td. You may need to parseInt before any mathematical formulas.
});
});
If you need clarification on anything, please let me know.

Dynamically generate id for input text box

I have create text boxes using json data.
Now, I want to generate ids for these dynamically generated text boxes so that I can get the value for the text boxes.
I need the code that can generate ids for text box created using json objects.
While you're looping through the objects you want to create, use the index to create an id (or better yet, append the index like id: 'foo-' + index.
Here is an example. The JSFiddle might give you some inspiration.
$(function () {
var json = '[{"foo":"bar","quux":1},{"foo":"bar","quux":2},{"foo":"bar","quux":3}, {"foo":"bar","quux":4}]',
container = $('#container');
$.each(JSON.parse(json), function (index, obj) {
container.append($('<input/>', {
id: index,
value: 'my id is' + index
}));
});
});
Please clarify if this does not answer your question.

how to construct JSON before submitting form using javascript

I have the following demo on jsFiddle. I would like to submit this form using javascript and send a JSON object back to my controller.
As you can see multiple rows can be added to the table and submitted. In my JSON data I would like to keep track of which checkboxes got clicked for which rows. So for example, based on the below screen shot:
I would like the JSON object to look like this:
{light:[{red:on}, {yellow:off},{green:on}], dark:[{red:off}, {yellow:off},{green:on}]}...
The code I came up with looks like this:
var jsonObject = {};
$('.input-row').each(function(index, row) {
var innerObject = {};
$(':checkbox', row).each(function(index, checkbox) {
innerObject[checkbox.name] = checkbox.checked ? 'on' : 'off';
});
var key = $('input[type="text"]', row).val();
jsonObject[key] = innerObject;
});
console.log(jsonObject);
// use jsonObject somehow
We're creating an empty object that will be our overall JSON object (called jsonObject).
Then we're iterating over each of the rows of inputs (I've added an input-row class to these so they can be selected easily).
For each row, we create another empty object (called innerObject), then iterate over its checkboxes. For each checkbox, we add a property to innerObject: the key is the name attribute/property of the checkbox, the value is on or off depending on the checked state. Finally, we get the value of the text input on that row to use as the key in jsonObject, and add the property to it.
Here's a working example of the above code.
The easiest way to serialize a form as JSON is to use jQuery's serializeArray()
JSON.stringify($('form').serializeArray());
You should build your own JSON string and then use jQuery.parseJSON() to do this loop all your tr elements in the table and collect the information you need.
The below code is a start for you according the html in fiddler.
var strJSON = '';
$("#blacklistgrid tr").each(function (i) {
if (i != 0)
{
var currentRow = $(this)
strJSON += "{ " + currentRow.find("input[name='shade']").val() +"[{red: currentRow.find("input[name='red']").is(":checked")} ] }";
}
});
var theJSON = jQuery.parseJSON(strJSON);
please check the correct format for JSON string and I could not check the code if it working but you can get the logic here.

Populating multiple drop-down menus with static values

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

Categories

Resources