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.
Related
I'm trying to get all of the values on a 4th column of my datatable table. (both visible and unvisible rows).The 4th column of each row is consist of a checkbox. After I get them, I need to change 'checked' property of them and send back to table. Currently, I'm able to get data but I do not know how could I send them back to datatable after modifying. In the column that I'm trying to retrieve checkboxes are exist. Here is my code :
$(document).on('click', '#select_all', function()
{
var rows = $("#results_container table").dataTable().fnGetNodes();
var cells = [];
for(var i=0;i<rows.length;i++)
{
// Get HTML of 4rd column (for example)
console.log( $(rows[i]).find("td:eq(3)"));
}
});
Here is what console.log statement prints out :
[td.sorting_1, prevObject: jQuery.fn.jQuery.init[1], context: tr, selector: "td:eq(3)"]
The check property that I want to modify is under 0: td.sorting_1 -> childNodes screen shoot of my console view
So how could I changed this checked value and see the result on my datatable?
In your for loop store your data to a variable:
var dataHolder = $(rows[i]).find("td:eq(3)")
Then access your data like this:
dataHolder = dataHolder[0].childNodes;
Then try your console.log() on the dataHolder.
You should be able to change the value like this:
dataHolder[1].checked = true;
I'm trying to submit a complicated form with jQuery. I want to submit the values to the server in an AJAX Request.
Given this array of <tr> values that I've got from jQuery Datatable plugin, how can I easily extract the data-id values into a format suitable for submitting to the form e.g. something like:
{
id: 65537, id: 32768, id: 65539
}
I have tried:
> $(table.rows().nodes())
> [<tr role="row" class="odd" data-id="65537">…</tr>, <tr role="row" class="even" data-id="32768">…</tr>, <tr role="row" class="odd" data-id="65539">…</tr>]
> $(table.rows().nodes()).length
3
What code is needed to just get the data-id values?
Updated Edit
Actually, I've just tested the form by hardcoding the values, and I need to convert it to look like this 0 indexed array, obviously with the numbers from the id field:
var formData = {"products[0]": 65537,
"products[1]": 65540};
Thank you.
Use this and the data variable will have all you want
$(function(){
var data = [];
$.each($('table.rows().nodes()'),function(k,v){
data.push($(this).data('id'));
});
console.log(data);
})
Well just loop through each tr and push its data-id with unique key-value paid into an array.
DEMO
var rows=$(table.rows().nodes())
var values=[];
$.each($(rows),function(key,value){
var vals ={}
vals[key]=$(this).attr('data-id')//or values.push($(this).attr('data-id');
values.push(vals);
});
console.log(values);
Note : You cannot have duplicate keys in an object say id as mentioned in your question so better use some unique index which you can obtain from key parameter of $.each
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);
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.
I'm creating a dynamic form builder where table rows can be dragged, dropped, reordered and so on. Most of this is working but when it comes to deleting rows how would I created an array or set of values that I could post back to the php script that I am using to update the database.
The way I am going to handle it is create a delimited string and post this back.
How would I go about creating the the string dynamically by appending a value like the following: 23| every time the user clicks a button? For example the if user click the button 3 times the sting would be 23|25|26| and then when they clicked save that value could be posted back to be processed.
This is the code I have for the delete function so far but its only removing the table rows and not actually generating the string.
$(".reMove").live('click', function(e) {
$(this).parent().parent().remove();
var al = $(this).attr('rel');
$("#form1").find(".del").val(al);
e.preventDefault();
sortt();
});
I would use an array:
var deletions = [];
// When deleting
deletions.push(value);
// When sending to your PHP script, create a string via Array#join
var deletionsString = deletions.join("|");
Alternately, if you like, you can just use a string and append to it:
var deletions = "";
// When deleting
deletions += "|" + value;
// When sending to your PHP script
if (deletions.length > 0) {
deletions = deletions.substring(1); // Skip the leading "|"
}
...but I prefer the array route.
I can see you've got a form here. You could dynamically create a hidden input:
var $input = $('<input/>')
.attr('type', 'hidden')
.attr.('name', 'del[]')
.val(al);
$("#form1").append($input);
After posing this form back you could simply delete all records from $_POST['del'] array.
Maybe this is the solution you're looking for?