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.
Related
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!
I have some dynamically created filters on a web app's page where the filter "entry" is at times the combination of a few different inputs and the values for the collection are gathered into an array to send back to the server. If these were all just single inputs then an array of values would be easy to map over to the inputs on the backend, however when one or more is a multiselect with multiple options, a flattened array of values mixing the multiselect's values and the individual input values isn't appropriate.
As an example: if I have two inputs for a given filter on a search control page, one being a multiselect and another being a text input, I would like to gather an array of two elements, the first being an array of selected values and the second as the value entered in the text input. So if in the first multiselect I select "A", "B" and the text input I enter "Joe" and the code below gathers the input values:
Coffeescript:
filters = []
$(#customFilterElements.selector).each ->
filterName = $(#).find('.filter_entry .filter_name:input').val()
filterValues = $(#).find('.filter_entry .filter_value:input').map(->
if $(#).data('multiselect')
$(#).find('option:selected').map(->
$(#).val()
).get()
else
$(#).val()
).get()
filters.push({name: filterName, value: filterValues})
Javascript: (converted from above)
var filters = [];
$(this.customFilterElements.selector).each(function() {
var filterName, filterValues;
filterName = $(this).find('.filter_entry .filter_name:input').val();
filterValues = $(this).find('.filter_entry .filter_value:input').map(function() {
if ($(this).data('multiselect')) {
return $(this).find('option:selected').map(function() {
return $(this).val();
}).get();
} else {
return $(this).val();
}
}).get();
return filters.push({
name: filterName,
value: filterValues
});
});
Current result for filterValues: ["A","B","Joe"]
The above code ends up producing an array ["A","B","Joe"] for filterValues.
I think this may be because the .get() is converting everything to a flattened array. I tried using $.makeArray() instead of .get() and I get the same results but perhaps I missed something.
Desired result for filterValues: [["A","B"],"Joe"]
What I am hoping to produce is [["A","B"],"Joe"] so it is clear that the first element (in this example) is a collection of selected values from a multiselect to the backend.
How can I adjust the above code to get the desired result (for any combination or ordering of multiselects and single inputs together) in a fairly elegant manner?
The code is intended to be applied to any dynamically created filter, so reusable instead of hardcoding to each filter.
Ok, after a full night's rest the answer came to me right away and it seems so obvious now - just need to wrap the multiselect in an array bracket after the .get()! - doh. Sometimes documenting the problem here forces a solution to bubble up or highlight what I was missing.
filters = []
$(#customFilterElements.selector).each ->
filterName = $(#).find('.filter_entry .filter_name:input').val()
filterValues = $(#).find('.filter_entry .filter_value:input').map(->
if $(#).data('multiselect')
[$(#).find('option:selected').map(->
$(#).val()
).get()]
else
$(#).val()
).get()
filters.push({name: filterName, value: filterValues})
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.
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];
});
I'm looking to get a bunch of checkboxes (all with the same class) and get all the attribute names and push all the checked boxes into an array (also remove them from the array if they get unchecked).
Eventually, I want to pass an array of what was checked via ajax, and the ajax refreshes every time a box is checked/unchecked.
Any ideas on how I'd do this?
Use $.map to get all the names of checkboxes in an array.
var names = $('.theClassName').map(function() {
return this.name;
});
For second part of your question.
To get only checked checkboxes use $('.theClassName:checked'). You don't have to maintain an array for this.
Try the following
var names = [];
$('.theClassName').each(function() {
var name = $(this).attr('name');
names.push(name);
});
var names = $('input.class_name:checked').map(function {
return $(this).attr('name');
})
will fill an array with the names of the checked checkboxes.