Reputation: 109
I'm working on the User role permissions and for that I've created a form like this:
The generated HTML for each checkbox is
<div class="checker" id="uniform-department_create">
<span>
<input type="checkbox"
class="form-control department"
id="department_create"
name="department_create"
value="create">
</span>
</div>
now onSubmit
I'll be calling a function that would pull the user's permissions. It looks like this:
var designationForm = {
// All permissions must be added to this Array
// to manipulate checkboxes
permissions: Array('department','customer','designation'),
...
get_permissions: function() {
var allowed = Array();
$.each(designationForm.permissions, function(index, permission) {
allowed[permission] = Array();
$.each($("."+permission),function(input, value) {
if ($("#uniform-"+$(value).attr('id') + " span").hasClass('checked')) {
allowed[permission] += "{"+$(value).attr('value')+":"+"true},";
} else {
allowed[permission] += "{"+$(value).attr('value')+":"+"false},";
}
});
return allowed[permission];
});
// console.log(allowed);
return allowed;
},
...
}
what it does is basically check permissions array and iterate through all permissions if it finds a checkbox's span containing the class "Checked" it adds it to the allowed array.
if I console
the result then I can see correct return but I'm unable to return the resultant array.
Upvotes: 1
Views: 68
Reputation: 28611
if I console the result then I can see correct return but I'm unable to return the resultant array.
and
its returning empty array
Copying the code and adding some extra divs/spans into jsfiddle: jsfiddle.net/fk2x8w9x/1 and looking at the console output gives:
[department: "{create:false},{delete:false},", customer: "{create:true},", designation: Array[0]]
ie, an empty array as described, but with the values set as properties of the "array".
This is because:
obj.val =
but also set properties via indexer, such as obj["val"] =
This is what is happening here - properties are being added instead of array "items".
If you change lines:
var allowed = Array();
allowed[permission] = Array();
to
var allowed = {};
allowed[permission] = {};
then it may make more sense.
Upvotes: 1