Create object property names using loop and input textboxes - javascript

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;

Related

Find current value with class jquery

I made this script:
var a = $(this).find('.q').val();
I'm trying to find the value for every .q input, but I seem to have got someting wrong. Can anyone explain to me what's wrong?
Update: I have multiple .q elements.
It sounds like you want to receive a list/array, like this:
["foo", "bar"]
where "foo" and "bar" are each values of .q elements.
If I'm right, here's what you want:
var listOfValues = $(this).find('.q').map(function() {
return $(this).val();
});
listOfValues will contain an array-like list of all values of each .q element. This is all thanks to the map function. More information here: http://api.jquery.com/map/
Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.
As you have multiple .q elements you need to loop over them:
$(this).find('.q').each(function() {
var val = $(this).val();
// do something with the value here...
});

Changing local variable in JavaScript affects original global with different name

I have a global declared at top of script:
var g_nutrition_summary = null;
When the user enters the page, I return network data and give this variable a value.
g_nutrition_summary = json.data;
This line is the ONLY assignment of the variable and is never called again (tested with alerts).
I later use that json.data variable to populate a Bar Chart with the plugin Chart.js. The global assignment is for later use.
Underneath the chart, the user can filter certain types of data it displays with a series of checkboxes. So my goal is, to keep an original value of what comes in from the network, and then make a LOCAL COPY of it and alter the COPY (not the global original) and repopulate the chart. Everytime the user checks/unchecks a checkbox, it will call this function and grab the ORIGINAL global (g_nutrition_summary) and re-filter that.
Here is how I do it:
function filter_nutrition_log()
{
alert("1: " + JSON.stringify(g_nutrition_summary));
// reassign object to tmp variable
var tmp_object = g_nutrition_summary;
var food_array = new Array("Grains", "Vegetables", "Fruits", "Oils");
var checked_array = new Array();
// Make an array of all choices that are checked
$(".input-range-filter").each(function()
{
var type = $(this).val();
if ($(this).is(':checked'))
{
checked_array.push(type);
}
});
alert("2: " + JSON.stringify(g_nutrition_summary));
// Loop thru all the 7 choices we chart
$.each(food_array, function(i, val)
{
// find out if choice is in array of selected checkboxes
if ($.inArray(val, checked_array) === -1)
{
// it's not, so delete it from out tmp obj we
// will use to repopulate the chart with
// (we do not want to overwrite the original array!)
delete tmp_object["datasets"][val];
}
});
// Resert graph
alert("3: " + JSON.stringify(g_nutrition_summary));
getNutritionChart(null, tmp_object, null, false);
}
Somehow, between alert "1" and alert "2". The global gets changed. Then when the user clicks a checkbox again and it calls this function, the very first alert shows that the original, global object contains the altered data to the tmp_object variable.
As you can see, I call a third party function I have created when this happens originally. Doing a search for the global there is absolutely nowhere else it is used in the instances described above.
Am I not understanding something about JavaScript variable scope?
Both objects and arrays in javascript are treated as references, so when trying to pass them to functions or to "copy" them, you are just cloning the reference
To have a "real copy", you would need to traverse the object and copy its content to another object. This can be done recursively, but fortunately jquery already comes with a function that does this: $.extend
So the solution would be:
var tmp_object = $.extend({},g_nutrition_summary);
If you have a nested object, you need to set an extra parameter:
var tmp_object = $.extend(true,{},g_nutrition_summary); // now it will do it recursively
For arrays, an easy way to make a "real copy" is, as #Branden Keck pointed out,
var arrCopy = arrOriginal.slice(0)
More on jquery extend: https://api.jquery.com/jquery.extend/
Going along with juvian's comment. To create the new array as somewhat of a "copy" and not just a reference, use:
var tmp_object= g_nutrition_summary.slice(0);
However, .slice() is only works for arrays and will not work on JSON, so to used this method you would have to create an array from the JSON
Another method that I found (although not the cleanest) suggested creating a string from the JSON and re-parsing it:
var tmp_object= JSON.parse(JSON.stringify(g_nutrition_summary));

Store function result to variable

How can I store the result of a function to a variable?
In navigating an object that contains an array, I am looking for one value, value1, once that is found I want to get the value of one of its properties, property1.
The code I am using below is an example and is incorrect.
function loadSets(id){
clworks.containers.find(function(i){
return i.get('property1')===id;
});
}
My intent is to navigate the object below:
clworks.containers
containers[0].property0.id
containers[1].property1.id
I am trying to determine how to find which item in the array has a property value equal to the id used in the function and then store it as a variable.
Simply:
var myVar = loadSets(id);
EDIT
Ok, as much as I understand your question now, your situation is the following:
You have an array containing objects called containers;
You want to iterate through this array, looking for the property id of the property property1 which equals the one specified in the function called loadSets(id);
Once found, store the object with the requested id in a variable.
Am I right?
If so, this should solve your problem:
// This function iterates through your array and returns the object
// with the property id of property1 matching the argument id
function loadSets( id ) {
for(i=0; i < containers.length; i++) {
if( containers[i].property1.id === id )
return containers[i];
}
return false;
}
After this you just need to do what I said in the first answer to your question, triggering it however you want. I put up a quick JSBin for you. Try to put 10, or 20, in the input field and then hitting the find button; it will return the object you are looking for. Try putting any other number, it will return a Not found.
Currently your function, loadSets, isn't actually returning anything and so you cannot store a result from it.
Try:
function loadSets(id){
return Base.containers.find(function(i){
return i.get('entityid')===id;
});
}
And to get a result into a variable:
var result = loadSets(id);

Variable name is getting added instead of its value , in javascript object [duplicate]

I have a problem while adding values to a JavaScript object: the value to add is a key,value pair. Here is sample:
//JavaScript object
var cart=new Object();
function add()
{
var rating="1"
var category="somecat";
var user="user1";
if(cart[user]==null)
cart[user]={category:rating};
else
cart[user][category]=rating;
}
What I was expecting is that if user exists in cart object then value for his particular should get replaced, and if user doesn't exist then new user and category should be added.
The code is working fine when user already exists. Problem is, when I am adding a new element with cart[user]={category:rating} then its adding the variable name as key i.e. category , not the value inside it ("somecat").
Is there any way to do this using json, jquery or javascript itself?
Is there any way to assign value inside the variable?
There is no way to use a variable to define a property name inside object literal notation. It accepts identifiers or strings, but both identify property names, not variables.
You have to create the object then add the property:
if(!cart[user]) {
cart[user] = {};
}
cart[user][category] = rating;
You will need to replace
{category:rating}
with
var obj = {};
obj[category] = rating;
When creating an object literal the key must be a string, so in your code it will be "category". If instead you do:
var rating="1"
var category="somecat";
var user="user1";
if( !cart[user] ) {
cart[user]={};
}
cart[user][category]=rating;
That will initialise a non existing user to an empty object and then add the category.

How to set certain element values to null in JavaSctipt

I have some items I am storing in an element that get added at various times like this:
document.getElementById('rout_markers').value = str;
I am not too good with JavaScript, but as I understand it, the values get stored as an array, correct?
What I need to do is to be able to remove all the elements or to be able to remove the last element that was added.
How can I do that?
Thanks!
If you're assigning str to an element then there are no arrays involved here - you'll be overwriting each previously-assigned value with the latest and thereby storing only the latest value.
You could use an array but you'd have to know the location of each item in the array, so if you wanted to assign or nullify a specific element in your array, you'd have to a have a record of where it was - although you could get around that it with a multi-dimensioned array, where the first element at each index is the name of the property, and the second element at each index is that value of the property.
If you want to store multiple properties in a field in order to retrieve them all later, there are two simple ways of doing this.
Consider using either a field for every property.
If you do this then I'd suggest using a naming convention for the fields so that you can more easily assign the property.
Concatenating a string to form a collection of key-value pairs, very much like a query-string.
In the example you gave, this would mean storing something like:
var keyVals = 'route_markers' + '=' + str + '&';
document.getElementById('myHiddenProperties').value = keyVals;
When you want to assign another property to this string you do something like this:
keyVals = document.getElementById('myHiddenProperties').value;
keyVals += 'new_property' + '=' + myNewValue + '&';
document.getElementById('myHiddenProperties').value = keyVals;
In this way, if you want to remove a specific key-value pair, you split the stored value like this
var arrKeyVals = document.getElementById('myHiddenProperties').value.split('&');
You then have an array of key-value pairs.
If you want to retrieve a value from this array, or blank one of the values then loop through this array, splitting each into its key and value, like this:
for (var i = 0; i < arrKeyVals.length; i++) {
var keyVal = arrKeyVals[i].split('=');
var key = keyVal[0];
var val = keyVal[1];
if (key == name_of_key_sought) {
val = ''; //assign an empty string to this property to forget about it
}
}
I am not too good with JavaScript, but as I understand it, the values get stored as an array, correct?
No, the value property of certain HTML elements is just a string value. (And it only exists on certain elements, like input.) Assigning a new value to value will overwrite the previous value, not store it in an array.
What I need to do is to be able to remove all the elements or to be able to remove the last element that was added.
This part of the question sort of goes away because of the answer to the first part, but you can clear the value property by assigning an empty string to it.
If by any chance you mean remove/hide the element itself (the text box) then you can have such code:
document.getElementById('rout_markers').style.display = 'none';
Otherwise the other answers here cover it all nicely.

Categories

Resources