So I'm storing checkbox data in an object that is stored with Parse.com. This is working correctly and is storing the object as follows:
Object {c1: false, c2: false, c3: false}
Where 'c1'=id of the checkbox and false obviously is the boolean value for unchecked.
I'm trying to create a function that queries that object and then rewrites the checkboxes with the properties. Here is my attempt at that:
var Checklist = Parse.Object.extend("Checklist");
//get checkboxes from parse and load them onto screen
function getChecklist()
{
var user = Parse.User.current();
var q = new Parse.Query(Checklist);
q.include("user");
q.equalTo("user", user);
q.descending("createdAt");
q.find({
success: function(results)
{
//this variable will need to change to be associated with the user's checklist
var i=0;
var check = results[i].get("check");
//takes object check and sorts it into order
var sortedKeys = Object.keys(check).sort();
console.log(check[Object.keys(check)[0]]);
//ATTEMPT AT checking the boxes correllated to the sorted keys id for each checkbox
for (var id in check)
{
$("#" + id).attr("checked", sortedKeys[id]);
console.log(check);
}
}, error: function(error){
console.log("Query Error:"+error.message);
}
});
};
getChecklist();
The 'check' is a column of checklist where the object is stored on Parse. As of now, I am unable to set the sortedKeys ('c1''c2''c3'etc.) to the checkboxes and furthermore cannot associate the boolean properties of those keys with the checkstate.
Any advice? Here is a gist with the whole html+script if further information is needed/wanted. https://gist.github.com/ripplep/75627c25ade7c5e57883
P.S. I apologize if the code is formatted inconsistently, as I am fairly new to programming.
EDIT with correct code:
function getChecklist()
{
var user = Parse.User.current();
var q = new Parse.Query(Checklist);
q.include("user");
q.equalTo("user", user);
q.descending("createdAt");
q.first({
success: function(checklist)
{
//this variable will need to change to be associated with the user's checklist
var check = checklist.get("check");
console.log(check);
//takes object check and sorts it into order
//console.log(check[Object.keys(check)[0]]);
//ATTEMPT AT checking the boxes correllated to the sorted keys id for each checkbox
for (var id in check)
{
$("#" + id).attr("checked", check[id]);
console.log(check);
}
}, error: function(error){
console.log("Query Error:"+error.message);
}
});
};
i would advice to simplify it to prevent this troubling code.
given working fiddle example
the main idea is just loop the object using:
var obj = {c1 : false, c2 : true, c3 : false }
for (var id in obj) {
$("#" + id).attr("checked", obj[id]);
}
please see fiddle to complete solution.
Related
I have a ramdom array in javascript
var dataModel = [];
I've queried an oData url and I want to fill the result in my dataModel [] array. And, for each item I want to add additional fields
odataMod.read(
"/",
null, [],
true,
function (oData, oResponse) {
var data = oData.results;
data.forEach(function (item) {
//Add the object
dataModel.push(item);
//I want to add additional fields to every object in data
dataModel.push(item.ObjectType = "Chevron");
dataModel.push(item.HierarchyNodeLevel = 0);
dataModel.push(item.IsCriticalPath = false);
dataModel.push(item.IsProjectMilestone = false);
dataModel.push(item.DrillDownState = "expanded");
dataModel.push(item.Magnitude = 5);
...
Note : the ObjectType , DrillDownState , Magnitude (etc...) are the fields that I want to add with their values Chevron, 0, false (etc...)
Below is a screenshot of the current result :
But I want to add the additional properties inside each item and not outside , what I am doing wrong? In other word, I want the additional fields to be inside the metadata
Below is a sc of where I would like to add the items :
Maybe I'm misunderstanding, but I think you want only one push per item in the response. The other pushes ought to be replaced with setting properties on a copy of the item...
data.forEach(function (item) {
item.ObjectType = "Chevron";
item.HierarchyNodeLevel = 0;
item.IsCriticalPath = false;
item.IsProjectMilestone = false;
item.DrillDownState = "expanded";
item.Magnitude = 5;
dataModel.push(item); // note: just one push
// alternatively, so as to not mutate item...
// const dataModelItem = Object.assign({
// ObjectType: "Chevron",
// HierarchyNodeLevel: 0,
// etc.
// }, item);
// dataModel.push(dataModelItem);
}
I am using two different array object initialPermissionArr[item.id] and newPermissionArr[roleId] in two different functions
function(item){
vm.initialPermissionArr[item.id] = item.permissions.map(function (permission) {
permission.status = true;
return permission;
});
}
staticArr[item.id] = item.permissions.map(function (permission) {
permission.status = true;
return permission;
});
newpermissionArr[item.id] = vm.initialPermissionArr[item.id];
Below function updates the array, if same object is found it updates the status and if new object is found it pushes to newPermissionArr
function onChanageOfPermission(roleId,item) {
var flag = false ;
for (var key in newpermissionArr[roleId]){
if(newPermissionArr[roleId][key].id == item.id){
flag = true;
newPermissionArr[roleId][key].status = item.status;
break;
}
}
if (!flag) {
newPermissionArr[roleId].push(item);
}
}
So when newPermissionArr[roleId][key].status = item.status; is updated it also update the status in the initialPermissionArr[item.id] also.
And initial declaration is
var newPermissionArr = [];
var staticArr = [];
where for eg item is
{
roleId : 1,
permissions : [{"name": "A", "id" : 1},{ "name" : "B", "id" : 2 }]
}
I need initial object Array to remain same and at the end i need to compare the initial array with the modified array and need to find the reference however on updating the status it updates in both array. How to avoid this ?
The arrays reference the same object. To modify just one of them, you should use slice() function for clone the array:
newpermissionArr[item.id] = vm.initialPermissionArr[item.id].slice();
This is happening because of following line of code
newpermissionArr[item.id] = vm.initialPermissionArr[item.id];
Here object is passed by reference, so whenever newpermission is updated intialpermission will also be updated.
To fix this just copy the intialPermissionArr to newPermissionArr.
Unfortunately,plain javascript does not have any function like angular.copy. So you will have to do this in following way-
newrPermissionArr[item.id] = JSON.parse(JSON.stringify(vm.intialPermissionArr[item.id]));
this should fix your problem.
When you assign something to a and b and it is a pointer in memory to object c. Then as soon as you change it to c2 both a and b will get c2 from that point as they were just pointers to same location.
I'm trying to put together a web form to mark an indeterminate number of employees as either present or absent. The page itself contains an arbitrary number of divs of the form:
<div class="employee" empID="9" presence="0">
The divs themselves contain the options, with 'presence' being changed to 1 or 2 using jQuery depending on the option selected.
When the 'submit' button is pressed, I'd like to convert this data into a parsable array of pairs of 'empID' and 'presence'. I've tried doing this with jQuery as follows:
$('.cic-button').click(function(){
var submitData = {employees:[]};
$('firedrill-employee').each(function(){
submitData.push({
employeeID: $(this).attr('empID'),
presence: $(this).attr('presence')
});
});
});
However, when this is done, the submitData variable is failing to populate. Any idea why? Am I going about this in the correct manner? Is what I'm trying to do even possible?
Many thanks.
You have a few errors. Make the class that you iterate over the collection of "employee" not "firedrill-employee" and don't forget the dot to indicate it's a class. Reference the employees array withing the submitData object. You can't just push an element into an object.
$('.cic-button').click(function () {
var submitData = {
employees: []
};
$('.employee').each(function () {
submitData.employees.push({
employeeID: $(this).data('empID'),
presence: $(this).data('presence')
});
});
console.log(submitData);
});
Fiddle
Js fiddle
$('.cic-button').click(function () {
var submitData = [];
$('.employee').each(function () {
var self = $(this);
// Create and obj
var obj = new Object(); // {};
obj["employeeID"] = self.attr("empID");
obj["presence"] = self.attr("presence");
//push that object into an array
submitData.push(obj);
console.log(obj);
console.log(submitData);
});
});
You need to specify the employee array as such:
$('.cic-button').click(function(){
var submitData = {employees:[]}; // employees is an array within submitData...
$('.firedrill-employee').each(function(){
submitData.employees.push({ // ...so amend code here to push to the array, not submitData
employeeID: $(this).attr('empID'),
presence: $(this).attr('presence')
});
});
console.log(submitData);
});
See example JSFiddle - http://jsfiddle.net/yng1qb6o/
I'm trying to check if I have something in an array already before adding - so that I cannot add the same type more than once. I am checking the model of the drop down I am selecting from against the array I am storing everything in (there is a slight difference in that the model stores the id as id and the array as skillId).
I am basically just trying to look through the array and see if the id matches - and if it does do not add the item to the array. Here is the code.
$scope.saveSkill = function() {
//send skill to get path, then add to skills array
console.log($scope.pathArray);
console.log($scope.scope5.id);
var skillCheck = true;
//check if exists aready
for(i=0;i<$scope.pathArray.length;i++){
if($scope.pathArray[i].skillId = $scope.scope5.id ){
console.log("Cannot add same skill more than once");
skillCheck = false;
}
}
if(skillCheck){
$http({
method: 'GET',
url: '/findPathScopeToSkill/' + $scope.scope5.id + "/1"
})
.success(function(data){
angular.forEach(data.paths, function(index) {
$scope.pathArray.push(index);
});
});
}
};
Just as a quick reference - pathArray is where the items get pushed into and where I do not want to have doubles - so I am checking the current id vs the id's inside the array (only difference is they are .skillId's)
I can add one, then can't add the same one again BUT I also can't add any after that. Can't seem to figure out what I am doing wrong here. Any help would be greatly appreciated. Thanks!
Ok, i know it might be simple for some guys, but i am trying this for hours and have no success till now.
if i have data in this array
var tDataValues = {
id: "TenantID",
text: "FullName",
username: "Username",
cnic: 'CNIC'
}
i am sending this variable to the function
commonSelect2Templating(selector,url,tDataValues,minInputLength,placeholder);
Note: I'm using Jquery Select2 (Sharing if it can help my question to understand.)
Then in that function in results Section i am trying to assign values
results: function(data, page) {
var newData = [];
var length = data.length + 1;
for(var i = 0; i<=length; i++){
}
$.each(data, function (index,value) {
newData.push({
id: value[tDataValues.id], //id part present in data
text: value[tDataValues.text] //string to be displayed
});
});
return { results: newData };
}
This is the data coming from the Server:
[{"TenantID":"13","FullName":"Rameez Hassana","Username":"Rameez","CNIC":"16141-6321136-1"},{"TenantID":"14","FullName":"Syed Haider Hassan","Username":"pakistanihaider","CNIC":"17301-5856870-1"},{"TenantID":"15","FullName":"Demo Tenant No 1","Username":"tn1","CNIC":"15165-6156685-6"}]
Coming to the The Problem:
Right now all the magic is happening here.
$.each(data, function (index,value) {
newData.push({
id: value[tDataValues.id], //id part present in data
text: value[tDataValues.text] //string to be displayed
});
Its Telling the code which is id and which is text, and it is working perfectly fine.
Now the Problem here is function i am trying to make is Common Function for the select2,
and if i have more values from db, like now i am getting from database how to make a loop and set those values one by one to its proper context.
e-g
tDataValues holds the fieldName cnic and server is sending the fieldName CNIC
so how to make a loop that if cnic exist in both then it should simply assign,
i can do that manually
newData.push({
cnic: value[tDataValues.cnic]
});
But like this it can not be a common function.
i can not simply make a logic how to implement this. did tried for hours but no success so far :(
Try:
for(var key in tDataValues) {
newData.push({ key: value[tDataValues[key]]});
}
Update:
then create an object first and push it to the array:
for(var key in tDataValues) {
var obj = {};
obj[key] = value[tDataValues[key]];
newData.push(obj);
}
check this, hope it helps
var mainData =[{"TenantID":"13","FullName":"Rameez Hassana","Username":"Rameez","CNIC":"16141-6321136-1"},{"TenantID":"14","FullName":"Syed Haider Hassan","Username":"pakistanihaider","CNIC":"17301-5856870-1"},{"TenantID":"15","FullName":"Demo Tenant No 1","Username":"tn1","CNIC":"15165-6156685-6"}];
var newData =[];
for(var i =0;i<mainData.length;i++){
for(var key in mainData[i]) {
var tempObj ={};
tempObj[key] = mainData[i][key];
newData.push(tempObj);
}
}
OUTPUT IS : [{"TenantID":"13"},{"FullName":"Rameez Hassana"},{"Username":"Rameez"},{"CNIC":"16141-6321136-1"},{"TenantID":"14"},{"FullName":"Syed Haider Hassan"},{"Username":"pakistanihaider"},{"CNIC":"17301-5856870-1"},{"TenantID":"15"},{"FullName":"Demo Tenant No 1"},{"Username":"tn1"},{"CNIC":"15165-6156685-6"}]