Replace the value of a key in a jquery object - javascript

I have created a modal plugin that has options defined by default or the user.
The majority of these values will be passed to a function and updated, when this happens, I want the value to be updated in the options. Ideally I don't want to have to update each individual one, and want to handle and update the object (options) as a whole.
the following is the users options:
modalDialog({
ID: 'before_unload',
title: 'opt.heading',
message: 'opt.text',
confirm: 'opt.confirm',
cancel: 'opt.cancel',
link: $(this).attr('href'),
});
Each of the options beginning with 'opt.' will have the function performed on them.
Here is the code for the modalDialog plugin that deals with the options
var options = $.extend(defaults, options);
return this.each(function() {
var o = options;
var reg = '^opt.*'; //regex to find all 'opt.' values
console.log(o);
$.each(o, function(i, v) { //for each value
if(i != 'save'){
if(v.match(reg)){ // match to regex
console.log(i+': '+v);
var newval = rc.getResource(v); // function to update value
console.log(newval); //value has been updated, function works
v = i.replace(i, newval); // update the index with new value
console.log('New i:v = '+i+': '+v); // checked and it works
//Now the question is, how do I update o (options with the new values?)
}
};
});
In the code above, lets pretend that rc.getResource(v) come back with a different farm animal name depending on which value gets passed to it, I update the value with my new farm animal name, and check that it all matches up and everything is working up until I get to updating the options. I have tried o = options.replace(i,v) and it come back with options.replace is not a function.
One thought I did have was after I have created a new value (performed my function) unset/delete the corresponding i:v and add the new value to the object, e.g.
i1 = i;
v1 = i.replace(i, newval);
o -= i:v;
o += i1:iv;
Alas, my brain is frazzled and am in desperate need of help, which would be greatly appreciated!

Can't you just do this?:
o[i] = v;

Related

Iterating over and comparing properties of two arrays of objects

I have set up a HBS helper which takes in two arrays of objects (users privileges). What I want to do is compare them and inject back into the template the privileges the user does and doesn't have.
Presently I can compare the names of the privileges with the following code:
hbs.registerHelper('selected', function(option, value){
var i;
var j;
var privName;
var userPriv;
var privObj = new Object();
var privArray = [];
for(i in option){
console.log('each ' + JSON.stringify(option[i]));
privName = option[i].privname;
for (y in value){
if(privName == value[y].privname){
userPriv = value[y].privname;
console.log('user has the following privileges', value[y].privname);
privObj = new Object();
privObj.name = userpriv;
privObj.id = value[y]._id;
privObj.state = 'selected';
privArray.push(privObj);
} else if (privName != value[y].privname){
console.log('user doesnt have priv ', privName);
privObj = new Object();
privObj.name = option[i].privname;
privObj.id = option[i].id;
privObj.state = '';
privArray.push(privObj);
}
}
}
console.log('privileges array ', privArray);
return privArray;
});
This works OK when the user only has one privilege, however when the user has more than one, for example two privileges, it returns the privileges twice. If the user has 3, thrice and so on. I know this is because the array is looping again because their are 2, 3 etc in the .length. However I can't seem to find an adequate solution.
Any help?
P.S. it would be nice if the Array.includes() method allowed you to search object properties.
The problem creating new objects the way you did is that for each property you add to your privilege-entity you will have to return to that function and set that property as well. You can instead just add/alter the state property of the existing objects:
hbs.registerHelper('selected', function(option, value) {
var names = option.map(function(opt) {
return opt.privname;
});
value.forEach(function(val) {
val.state = names.indexOf(val.privname) >= 0 ? 'selected' : '';
});
return value;
});
Basically:
The variable names is being mapped to be an array only with the privnames. You can check by using console.log(names).
The Array.forEach() function is helpful in this case because you just need to iterate over each object inside value and set its state-property.
To check if the privname exists, you just need to check the index in the previous names-mapped-array. For such a simple thing I used ternary operator (?:).
Finally, you return value, which is the array containing the objects you had updated.

Numerically ordered ID's of data objects in Firebase

I am pretty new to the 'game' and was wondering if it's possible to order newly added data (through a form and inputs) to the Firebase numerically so each new data entry gets the ID (number of the last added data +1).
To make it more clear, underneath you can find a screenshot of how data is currently being added right now. The datapoint 0-7 are existing (JSON imported data) and the ones with the randomly created ID belong to new entries. I would like to have the entries to comply to the numbering inside of my Firebase, because otherwise my D3 bar chart won't be visualised.
var firebaseData = new Firebase("https://assignment5.firebaseio.com");
function funct1(evt)
{
var gameName = $('#nameInput').val();
var medalCount = $('#medalsInput').val();
var bool = $('#boolInput').is(':checked');
firebaseData.push().set({games: gameName, medals: medalCount, summergames: bool});
evt.preventDefault();
}
var submit = document.getElementsByTagName('button')[0];
submit.onclick = funct1;
UPDATE:
function funct1(evt)
{
var gameName = $('#nameInput').val();
var medalCount = $('#medalsInput').val();
var bool = $('#boolInput').is(':checked');
for (var i = 0; i < 10; i++)
{
firebaseData.child('7' + i).set({games: gameName, medals: medalCount, summergames: bool}(i)); };
Problem:
There are two ways to generate ids for your document nodes.
Calling .push() on your reference will generate that unique id.
Calling .set() on your reference will allow you to use your own
id.
Right now you're using .push().set({}), so push will generate an new id and the set will simply set the data.
// These two methods are equivalent
listRef.push().set({user_id: 'wilma', text: 'Hello'});
listRef.push({user_id: 'wilma', text: 'Hello'});
Using .set() without .push() will allow you to control your own id.
Using .push():
When managing lists of data in Firebase, it's important to use unique generated IDs since the data is updating in real time. If integer ids are being used data can be easily overwritten.
Just because you have an unique id, doesn't mean you can't query through your data by your ids. You can loop through a parent reference and get all of the child references as well.
var listRef = new Firebase('https://YOUR-FIREBASE.firebaseio.com/items');
// constructor for item
function Item(id) {
this.id = id;
};
// add the items to firebase
for (var i = 0; i < 10; i++) {
listRef.push(new Item(i));
};
// This will generate the following structure
// - items
// - LGAJlkejagae
// - id: 0
// now we can loop through all of the items
listRef.once('value', function (snapshot) {
snapshot.forEach(function (childSnapshot) {
var name = childSnapshot.name();
var childData = childSnapshot.val();
console.log(name); // unique id
console.log(childData); // actual data
console.log(childData.id); // this is the id you're looking for
});
});
Within the childData variable you can access your data such as the id you want.
Using .set()
If you want to manage your own ids you can use set, but you need to change the child reference as you add items.
for (var i = 0; i < 10; i++) {
// Now this will create an item with the id number
// ex: https://YOUR-FIREBASE.firebaseio.com/items/1
listRef.child('/' + i).set(new Item(i));
};
// The above loop with create the following structure.
// - items
// - 0
// - id: 0
To get the data you can use the same method above to loop through all of the child items in the node.
So which one to use?
Use .push() when you don't want your data to be easily overwritten.
Use .set() when your id is really, really important to you and you don't care about your data being easily overwritten.
EDIT
The problem you're having is that you need to know the total amount of items in the list. This feature is not implemented in Firebase so you'll need to load the data and grab the number of items. I'd recommend doing this when the page loads and caching that count if you really desire to maintain that id structure. This will cause performance issues.
However, if you know what you need to index off of, or don't care to overwrite your index I wouldn't load the data from firebase.
In your case your code would look something like this:
// this variable will store all your data, try to not put it in global scope
var firebaseData = new Firebase('your-firebase-url/data');
var allData = null;
// if you don't need to load the data then just use this variable to increment
var allDataCount = 0;
// be wary since this is an async call, it may not be available for your
// function below. Look into using a deferred instead.
firebaseData.once('value', function(snapshot) {
allData = snapshot.val();
allDataCount = snapshot.numChildren(); // this is the index to increment off of
});
// assuming this is some click event that adds the data it should
function funct1(evt) {
var gameName = $('#nameInput').val();
var medalCount = $('#medalsInput').val();
var bool = $('#boolInput').is(':checked');
firebaseData.child('/' + allDataCount).set({
games: gameName,
medals: medalCount,
summergames: bool
});
allDataCount += 1; // increment since we still don't have the reference
};
For more information about managing lists in Firebase, there's a good article in the Firebase API Docs. https://www.firebase.com/docs/managing-lists.html

Javascript Form: Only Changed Fields

I have a php-site with a form on which i output preselected values via php. On form submit I want to check which values have changed and just submit these via javascript.
These are the preselected values I passed over from php. It's important that I keep the associative array structure.
var pbData = jQuery.parseJSON("{
"GameMode":"DEATHMATCH",
"Current Map":"VEGAS JUNKYARD",
"Current Missions":["VEGAS JUNKYARD","VILLA","PRESIDIO","KILL HOUSE","MURDERTOWN","CQB TRAINING","STREETS","THREE KINGDOMS CASINO","IMPORT\/EXPORT;"],
"RoundDuration":"3 minutes"}");
I marked the error in the code.
<script>
function displayVars(){
var form = document.getElementById('settings');
var elems = form.elements;
var txt = "";
for (var index = 0; index < elems.length; index++){
var selIndex = elems[index].selectedIndex;
if (typeof selIndex !== "undefined"){
//the Index Name in the json-object and the name of the form-field are the same
var idxName = elems[index].name;
//HERE is the problem. I want to access the subobject via a variablename, so i can iterate through it, but that doesnt work.
console.log ("pbData default = "+pbData.idxName); //always undefined
if (elems[index].value !== pbData.idx_name){
//building a POST-Url
txt = txt + elems[index].name + "=" + elems[index].options[selIndex].value+"&";
}
}
}
console.log (txt);
return false;
}
</script>
I know that I could do this differently, also with jQuery. In my case as I have the preselected values as a php-variable in any case, i think it's easier like this.
I would really like to know how I can iterate through the subobjects via a variable that contains the object names.
This is due to how you'e trying to access the property of the (JSON) object. Consider
var o1 = {idxName: true},
o2 = {foo : 'bar'},
idxName = 'foo';
o1.idxName; // true
o2.idxName; // undefined
o2[idxName]; // 'bar'
You need to access the property via pbData[idxName].
Additionally, you're not escaping quotes in your JSON string, and line breaks need to be escaped as follows
var pbData = jQuery.parseJSON("{\
\"GameMode\":\"DEATHMATCH\",\
\"Current Map\":\"VEGAS JUNKYARD\",\
\"Current Missions\":[\"VEGAS JUNKYARD\",\"VILLA\",\"PRESIDIO\",\"KILL HOUSE\",\"MURDERTOWN\",\"CQB TRAINING\",\"STREETS\",\"THREE KINGDOMS CASINO\",\"IMPORT\/EXPORT;\"],\
\"RoundDuration\":\"3 minutes\"}");
In Javascript you could keep an object or array with initial values and only post those values that are changed.
But in fact, I would do something similar, but in PHP. You can keep the original values in the session and compare the posted values to those initial values to see what has changed. That way, you won't depend on Javascript. Not only may Javascript be disabled, but also, a fast user may theoretically post the form before the Javascript has run. To move this check to PHP eliminates that risk.

jQuery list of data

I have a series of editable lists which, on a press of a button should be transformed into some sort of data structure. When it has been turned into some sort of data I need to add duplicates together.
Example:
200g banana
100g apple
200g apple
Should be turned into a data list of some sort and should in the end look like this:
200g banana
300g apple
Here's my attempt:
//button click event
$(".calculate").bind("click", function(e)
{
//get the correct parent of the button
var parent = $(this).closest("#calc");
//get relevant data
parent.find(".options").each(function(index, element)
{
var opt1 = $(this).children(".opt1").children("input").val(); //weight
var opt2 = $(this).children(".opt2").children("input").val(); //ingredient
});
});
Basically I click the button and the above script finds all the relevant data.
How can I turn this into a multidimensional array or a list of objects I can search for duplicates in?
When I try to make a dynamic object it seems to fail and when I make a multidimensional array to search in I get blocked by inArray's inability to search through them.
Problem recap:
I am able to get the user data no problem. Turning it into a list and adding together duplicates is the problem.
I will suggest you to have a global object that will contain the summary, this will look like this:
$(".calculate").bind("click", function(e)
{
var fruits = {};
//get the correct parent of the button
var parent = $(this).closest("#calc");
//get relevant data
parent.find(".options").each(function(index, element)
{
var opt1 = $(this).children(".opt1").children("input").val(); //weight
var opt2 = $(this).children(".opt2").children("input").val(); //ingredient
// here is my code
if(fruits[opt2] == undefined) {
fruits[opt2] = opt1;
} else {
// assuming that opt1 is an integer
fruits[opt2] += opt1;
}
});
// use fruits variable here
});
Here's another variant, which also does some simple parsing in case you have 100g as input, versus 100. Also, the data structure gets reinitialized every time, so everything does not get doubled on every click.
$(".calculate").bind("click", function(e)
{
//get the correct parent of the button
var parent = $(this).closest("#calc");
var ingredients = {};
var extractWeight = function (input) {
// you can add other logic here
// to parse stuff like "1kg" or "3mg"
// this assumes that everything is
// in grams and returns just the numeric
// value
return parseInt(input.substring(0, input.length - 1));
}
//get relevant data
parent.find(".options").each(function(index, element)
{
var opt1 = $(this).children(".opt1").children("input").val(); //weight
var opt2 = $(this).children(".opt2").children("input").val(); //ingredient
// initialize to 0 if not already initialized
ingredients[opt2] = ingredients[opt2] ? ingredients[opt2] : 0;
ingredients[opt2] += extractWeight(opt1);
});
});​
Here are some tips:
{} is called an object literal and is used to create a new empty object
object members can be accessed dynamically through the [] notation (i.e. if x === "name" then o[x] === o.name)
variables are visible inside functions that are at the same level or deeper in the scope - like in my example I use ingredients in the each function.
arrays in JavaScript only support numeric keys, so you won't have stuff like PHP's "associative arrays". Objects fill this gap in JS.
Here is a jsFiddle that does what you're looking for :) http://jsfiddle.net/LD9TY/
It has two inputs, one for the item name and the other for the amount. When you click add, it checks an object to see if the item was already added. If so, it increments the amount for that item based on your input. If not, it adds that item with the amount you specified. It then goes and builds a ul with all the items in your "store".
Note that this is a quick and dirty example, so there is no type checking or validation going on :)

JavaScript: Why isn't my closure working?

The following code is only assigning the value of the last .enter_form input to the last MYAPP.list[0].responses[MYAPP.score.round].form[key] (where key is the only thing that varies). I think it's because only the last value of the key is being passed to addEntry(), but I can't figure out how to get around that.
$('.enter_form input').each(function() {
var key = $(this).attr('id');
var val = $(this).val();
userDict[key] = val;
MYAPP.list[0].responses[MYAPP.score.round].form = [];
function addEntry() {
return function(k) {
MYAPP.list[0].responses[MYAPP.score.round].form[k] = {'entry': userDict[k]};
}(key);
}
addEntry();
}
Your addEntry function is redundant since each iteration is already run inside it´s own scope so key and val are preserved properly (hope that explanation makes sense). Also the array you where inserting into was overwritten each iteration as well, so at the end of the .each() you end up with an array with only 1 value. It should also be an object rather then an array, even if the id's are numerical.
// you where overwriting this each iteration
MYAPP.list[0].responses[MYAPP.score.round].form = {};
$('.enter_form input').each(function() {
var el= $(this); // cache instead of creating a new jQuery object each time
var key = el.attr('id');
var val = el.val();
userDict[key] = val;
MYAPP.list[0].responses[MYAPP.score.round].form[key] = {'entry': userDict[key]};
}); // ); was also missing
Should work.
It's a bit hard to work out what it's meant to do, but I think this is probably it:
MYAPP.list[0].responses[MYAPP.score.round].form = [];
$('.enter_form input').each(function() {
var $this = $(this),
key = this.id,
val = $this.val();
userDict[key] = val;
MYAPP.list[0].responses[MYAPP.score.round].form[key] = {
'entry': val
};
});
That's based on your saying that "...key is the only thing that varies" (presumably $(this).val() also varies, but I took your point). It will add entries to MYAPP.list[0].responses[MYAPP.score.round].form for each of the form's input ids, as well as adding them to the userDict map.
As a side note, if the id values on the input elements aren't purely numeric, then I suspect you want to start with a blank object:
MYAPP.list[0].responses[MYAPP.score.round].form = {};
// ^^-- change is here
...rather than an empty array:
MYAPP.list[0].responses[MYAPP.score.round].form = [];
...although since arrays are objects, it works even if you're adding non-numeric properties.
Off-topic: No need for $(this).attr('id'). Just use this.id.

Categories

Resources