Splitting comma separated values into array from optgroup - javascript - javascript

I have some code like this:
var optgroup = $('#myselect').val();
var optarray = optgroup.split(',');
alert(optarray.join("\n"));
The first line returns something along the lines of "option1,option2,option3" if all three options are selected. I want it to return a separate result for each option. I have tried the above code but I keep getting the error:
Uncaught TypeError: undefined is not a function
I'm not sure what the error is about, any help would be appreciated. As a side note, when these values are separated, I'm going to cycle through the array and store each option on a different row of a table in SQLite.

If you want to have the list of possible selections you can use the following code:
var list = '';
$('#myselect option').each(function(){
list = list + $(this).val() + '\n';
});
console.log(list);

Related

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!

Nested each statement using variables

I'm trying to use two arrays to populate a couple of each statements instead of writing it out 20 times for every attribute.
Here's what I was thinking. The idea here is to get the data (stored in mainData). I need a number of objects from this data, so I put those in an array ($dataPoints). I'm taking all of this data an appending it to a table. I'm adding the data to specific rows with specific ids (stored in $tableIds).
So, the basic idea...for every item in $dataPoints, look up that part of the data and append it to the table in the place indicated by the ids in the same position in the array. Like so...
var $dataPoints = ['name','description','subtitle'];
var $tableIds = ['mNames','mDescription','mSubtitle'];
$.each($dataPoints, function(index, val) {
$.each(mainData.val[index].source_values, function(index, val) {
$("#matrix_datatable").find('#'+$tableIds[index])
.append($('<td class="tableCells">')
.append(val.value + '</td>')
)
});
});
However, this line:
$.each(mainData.val[index].source_values, function(index, val) {
is throwing an error:
Uncaught TypeError: Cannot read property '0' of undefined
What am I missing here? Is there a simpler way to do this?
EDIT: Note that this works perfectly.
$.each(mainData.subtitle.source_values, function(index, val) {
$("#matrix_datatable").find('#mSubtitle')
.append($('<td class="tableCells">')
.append(val.value + '</td>')
)
});
However, I don't want to write this out for the 20 different objects within mainData.
It looks like you probably meant:
mainData[val][index].source_values
Writing mainData.val literally looks for a key val in mainData.

Search for multiple values in single column of dataTable (possibly use array?)

I have a dataTable that is populated with items that are either in draft, pending approval, approved or denied. The statuses of the items is in one particular column.
I would like to search this column for multiple types of statuses.
For example, I would like to search for pending and approved items, and then redraw the table to only show those items that are either pending or have been approved.
The kicker is that I would like to have this search string change dynamically through a checkbox.
The search works with hard coded values:
$('#theTable').DataTable().search('Pending').draw();
and even
$('#theTable').DataTable().search('Pending'|'Approved').draw();
But I would like to change the search string (the 'Pending'|'Approved' part) dynamically, based on checkboxes.
So...
if($("#Pending").is(":checked")) {
searchString += 'Pending';
$('#theTable').DataTable().search(searchString).draw();
}
if($("#Approved").is(":checked")) {
searchString += 'Approved';
$('#theTable').DataTable().search(searchString).draw();
}
But this doesn't work. I have tried concatenating, using an array, using fnFilter rather than search, but nothing seems to work.
Any ideas??
This was solved by using an array to add the search items, and then run through the array and join them with a pipe.
The following is what was used:
var whatsSelected = [];
$.each($('.statusChk'), function () {
if ($(this).is(":checked")) {
whatsSelected.push('(?=.*' + $(this).val() + ')');
}
});
$('#theTable').DataTable().search(whatsSelected.join('|'), true, false, true).draw();
The added string of (?=.* , then turning off the regex (? I think that's what the false does) was needed to make this work.
It looks like it caches the search parameters until you execute the chained function draw(). Then it will send a call to the end point with the parameters in columns[n][data]: populated so you can handle them in your server side script.
I did something like this:
$("#ddlTeam").change(function () {
var val= this.value;
if(val>0){
$('#example').DataTable().columns(9).search($("#ddlDomObject").val());
$('#example').DataTable().columns(5).search(val).draw();
}else{
$('#example').DataTable().columns(5).search('').draw();
}
});

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.

TaffyDB: Select problems

I'm new to TaffyDB and haven't done a lot of javascript programming so I'm hoping that the problem I'm having is something simple. I'm trying to update a listbox with the options stored in the TaffyDB according to the selected client. When I do my select however, it is returning all the rows.
Below is the code I am using to update the listbox, along with the selectString used to do the query, and what's in the TaffyDB.
Anyone have any ideas why I am getting back all rows when I specify clientID = 1788?
I tried the select string with and without quotes around the column identifier.
// load existing user client projects if we have any
var lbProjects = document.getElementById('lbProjects');
lbProjects.options.length = 0;
var selectString = '{clientID:"' + clientID + '"}';
alert(selectString);
userProjects(selectString).each(
function (r) {
var option = new Option();
option.value = r.projectID;
option.text = r.projectName;
lbProjects.add(option, null);
});
What's in selectString:
{clientID:"1788"}
What's in the DB:
[{"clientID":"1788","projectID":"19"},
{"clientID":"1789","projectID":"24"},
{"clientID":"1790","projectID":"23"}]
Thanks for any help.
Aaron L. Bratcher
The problem was trying to use the selectString variable.
The line
userProjects(selectString).each(
now reads
userProjects({clientID: clientIDValue}).each(
I was supposed to be passing in an object array, not a string. {} in javascript creates an array of objects.

Categories

Resources