How do I use a dynamic parameter name when accessing a variable?
Example:
opener.document.form.namerow_3.value = this.cells[0].innerHTML;
opener.window.form.{varaible}.value=this.cells[0].innerHTML;
In this case, the variable would be namerow_3, which will change based on user selection.
How do I solve the problem?
If I understand your question correctly, you're trying to access a dynamic property of the form object. You can do that by accessing the object like this:
// Base example of how to access namerow_3
opener.document.form.namerow_3.value = this.cells[0].innerHTML;
// Example with static accessor name
opener.document.form["namerow_3"].value = this.cells[0].innerHTML;
// Example with variable
var propName = "namerow_3";
opener.document.form[propName].value = this.cells[0].innerHTML;
Since most regular objects in JavaScript are basically a hashmap, you can usually access an objects property by specifying it's key like you would an array's index (in this case, form["namerow_3"]).
Related
You can quite easily set a data attribute of any element with jquery using $('#elid').data('key', value). You can do the same using document.querySelector('#elid').setAttribute('data-key', value)
However, jQuery gives you a special ability that querySelector doesn't - the ability to add attributes of an arbitrary type (including functions, and I think promises, which is what I need).
So if you were to do $('#elid').data('key', function(){console.log('yes')}) with jQuery, and then $('#elid').data('key')(), it would log 'yes' to the console -- we can just assign a function to the element as a data attribute and run it whenever.
But we can't do the same with 'setAttribute' -- when we do it, it apparently just assigns a stringified form of the function to the data attribute, rather than the actual function.
I've provided example code here:
https://jsfiddle.net/8e1wyL41/
So how can I apply data to elements with plain javascript, just like jQuery, including the ability to have arbitrary functions or javascript objects as data attribute values?
jQuery#data() uses an internal object to keep track of data values. It does not update the element to have new or changed data-* attributes when setting data values. When retrieving a data value, if the internal object does not have a set value it will attempt to get it from the data-* attributes.
A overly simplified way of doing this without jQuery would be to just use an object and store your data on that
var element = document.querySelector("div");
element.customData = {};
//get data example, check if customData has a value first, if not use dataset
var someData = element.customData["somedata"] || element.dataset["somedata"];
//set
element.customData["somedata"] = function(){};
If you don't want to contaminate the element with arbitrary properties you could use a WeakMap, pending on browser support, to associate a data object with the element. This also allows for using a single object to maintain other element data objects as well. The key to the data object is the element object itself. And the data object will get deleted from the map automatically once the element is garbage collected
var dataMap = new WeakMap();
var element = document.querySelector('div');
var elementData = dataMap.get(element);
if(!elementData){
dataMap.set(element, elementData = {});
}
//get data example, check if data object has a value first, if not use dataset
var someData = elementData["somedata"] || element.dataset["somedata"];
//set
elementData["somedata"] = function(){};
.dataset sets or gets a DOMString of HTML data-*, though you can use Function() to call the function stored as string at HTMLElement.dataset
document.documentElement.dataset.fn = function fn(...args) {console.log(args)};
new Function("return " + document.documentElement.dataset.fn)()("yes");
I have an intention to set a field value of an object like this
$scope[nameOfField]=value;
which works if nameOfField is just field name.
However, if I define in $scope object "subObject":
$scope.subObject={};
var nameOfField='subObject.someSubField';
$scope[nameOfField]=12345;
this does not work. Apparently I can not address directly sub-object fields like this. I however do need to use nameOfField approach with sub-object fields, and appreciate hints how to make it work. I can not predict if subObject will be featured in nameOfField - it can be both name field and subObject.someSubField.
EDIT: Difference with the question Accessing nested JavaScript objects with string key is that I not only need to access value of object but modify it.
Well your current code would result into
$scope['subObject.someSubField']=12345;
which would be a syntax error. Correct would be
$scope[nameOfField1][nameOfField2]=12345;
So you need a function to archieve this. Here an example (obviously this has to be extended to support more then just the 2 levels):
var scope = {};
function setValue(scopeString, val){
var match = /(\w+)\.(\w+)/.exec(scopeString);
if(!scope[match[1]]) //create if needed
scope[match[1]] = {};
scope[match[1]][match[2]] = val;
}
function getValue(scopeString){
var match = /(\w+)\.(\w+)/.exec(scopeString);
return scope[match[1]][match[2]];
}
setValue('lvl1.lvl2', 1);
console.log(getValue('lvl1.lvl2'));
I want to take that._mCon.usa which have array of object's and put the data like key value
in _mUsa object,In the object instance I've name and path ,I try like following and its not working the _mUsa is not filled with data...any idea what im doing wrong here ?
_mUsa{
},
for(var i = 0; i <= that._mCon.usa.length; i++) {
that._mUsa[that._mCon.usa[i][name]] = that._mUsa[that._mCon.usa[i][path]];
}
this is that._mCon.usa with the name and path properties
Object properties are accessed using .propertyname, so it should be:
that._mUsa[that._mCon.usa[i].name] = that._mUsa[that._mCon.usa[i].path];
You use [name] when the property name is dynamic, and name is a variable containing the property name.
You can use [] with a literal string, e.g. ['name'] and ['path'], but there's little point to that; if the property is known, just use the normal dot notation.
I'm making some JS code, where I need to set a variable as a key in a JSON array with Javascript array.push():
var test = 'dd'+questNumb;
window.voiceTestJSON.push({test:{"title":""}, "content":{"date":""}});
Where questNumb is another variable. When doing that code, the part where I just write the test variable it just becomes to the key "test", so I have no idea of getting this to wok. How could it be? Thanks!
If you want variables as keys, you need brackets:
var object = {};
object['dd'+questNumb] = {"title":""};
object["content"] = {"date":""}; //Or object.content, but I used brackets for consistency
window.voiceTestJSON.push(object);
You'd need to do something like this:
var test = "dd" + questNumb,
obj = {content: {date: ""}};
// Add the attribute under the key specified by the 'test' var
obj[test] = {title: ""};
// Put into the Array
window.voiceTestJSON.push(obj);
(First of all, you don't have a JSON array, you have a JavaScript object. JSON is a string representation of data with a syntax that looks like JavaScript's object literal syntax.)
Unfortunately when you use JavaScript's object literal syntax to create an object you can not use variables to set dynamic property names. You have to create the object first and then add the properties using the obj[propName] syntax:
var test = "dd" + questNumb,
myObj = { "content" : {"date":""} };
myObj[test] = {"title" : ""};
window.voiceTestJSON.push(myObj);
{test:{"title":""}, "content":{"date":""}}
this is a JS object. So you are pushing an object into the voiceTestJSON array.
Unlike within JSON, JS Object property names can be written with or without quotes.
What you want to do can be achieved like this:
var test = 'dd'+questNumb;
var newObject = {"content":{"date":""}}; //this part does not need a variable property name
newObject[test] = {"title":""};
This way you are setting the property with the name contained in test to {"title":""}.
i am trying to get a value from a key stored on a string variable proyNombre, but whenever i call it via the common method "myAssociativeArray.MyKey", it gets the variable 'proyNombre' as the key, instead of getting its value and passing it as a key.
proyectos.each(function(index){
var proyNombre = this.value;
if(!(proyNombre in myArray)){ // whenever the variable is undefined, define it
myArray[proyNombre] = horas[index].value-0 + minutos[index].value/60;
}
else{
console.log(myArray.proyNombre); //This doesnt work, it tries to give me the value for the key 'proyNombre' instead of looking for the proyNombre variable
console.log(myArray.this.value); //doesnt work either
}
});
Try:
console.log(myArray[proyNombre]);
myArray is actually an object in javascript. You can access object properties with object.propertyName or, object['propertyName']. If your variable proyNombre contained the name of a property (which it does) you can use the second form, like I did above. object.proyNombre is invalid - proyNombre is a variable. You can't do for example:
var myObject = {};
myObject.test = 'test string';
var s = 'test';
console.log(myObject.s); // wrong!!
but you could then do:
console.log(myObject.test);
console.log(myObject['test']);
console.log(myObject[s]);
You need to use the same syntax you used to set the value:
console.log(myArray[proyNombre]);
Simply access the value with myArray[proyNombre].
You're doing it right in the assignment: myArray[proyNombre]. You can use the same method to retrieve the variable.
If you change:
console.log(myArray.proyNombre);
console.log(myArray.this.value);
to
console.log(myArray[proyNombre]);
console.log(myArray[this.value]);
You should get the same value (the value for the key represented by the variable proyNombre) logged twice.
It's true that Javascript doesn't have associative arrays but objects in Javascript can be treated like associative arrays when accessing their members.