How can I post a bunch of checkbox names to an array? - javascript

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.

Related

Submitting multiple inputs with same name

Ok, so I have form for creating polls. I want to use AJAX request and able user to attach image instead of question, so I use FormData for this.
I could't find any solution for working with multiple input with same name (named like this: "name[]"). I tried this option:
var fdata = new FormData();
fdata.append('answers[]', $('input[name="answer[]"]').val());
But it doesn't work. I know I could use .each(), but I don't want different name for each question, so I don't have to rebuild PHP side too much.
Thanks for any help.
You have to append each value in turn. Currently you are only appending the first one (because that is what val() returns.
$('input[name="answer[]"]').each(function (index, member) {
var value = $(member).val();
fdata.append('answers[]', value);
});
The problem is $('input[name="answer[]"]').val() isn't giving you what you need; it returns the first input element's value. Instead, you want an array of values:
var values = [];
$('input[name="answer[]"]').each(function(i, item) {
values.push(item.value);
});
fdata.append('answers[]', values);
http://jsfiddle.net/j5ezgxe9/

How to append items to a blank array?

I have a ul-li block for image listing.On clicking on an corresponding images should delete and a value inside a <span>,which is sibling of image should be stored in a variable.Each time when I click,img should delete and each <span>'s value should be appended to jquery array variable.I did it,but when I alert the array variable it shows the single value of the current click only.ie not appending values generated through the previous click.
My JavaScript:
function delImg(newthis){
var Ids= [];
$(newthis).parent().hide();
var Id = $(newthis).siblings('.hidden').html();
Ids.push(Id);
alert(Ids);
return Ids;
}
The problem is alert(Ids) gives single variable instead of array.
Put the declaration of the array outside of the function (so you're not resetting it every time):
var ids = []
function delImg(newThis){
$(newThis).parent().hide();
var id = $(newThis).siblings('.hidden').html();
ids.push(id);
return ids;
}
Also, naming conventions suggest that you should camelCase your variable names, so I have done that.
You need to declare your array outside the function
var Ids = [];
function delImg(newthis){
// ...
}

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.

Create object property names using loop and input textboxes

I am refactoring some code where I grab the values inputted into textboxes and use said values for calculations. The problem is rather than using document.getElementByID multiple times I want to loop through each textbox on the page and assigning each value to this object which I will pass to my calculation functions. I would also like to set the property names of this object by looking at the input textbox IDs and using the ID strings for the object property names.
See code below:
$(document).ready(function() {
var calcObj = new Object();
$("input[id^='txt']").each(function(i, val) {
calcObj[i] = this.value;
});
$.each(calcObj, function(i, val) {
// alert(val);
});
});
As you can see when document is ready, object is created. There is a jquery .each loop to go through every input with id that contains txt. I am assigning this.value to object where index is i.
So I want to some how name the properties of this object and assign value so I can reference object property name elsewhere in the code where I pass this object to another function.
Thanks.
As far as I understand, you want:
calcObj[this.id] = this.value;
I don't exactly get what you're asking for, because it seems like you're already doing what I think you're asking.
Right now, you're doing:
calcObj[i] = this.value;
That's no different from assigning it like:
calcObj['foo'] = this.value;
// and later we can access that via
alert( calcObj.foo ); // or calcObj['foo']
You can be dynamic with that as well, like:
calcObj[this.id] = this.value;

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