Javascript Element.onclick = functionName(as String)? [duplicate] - javascript

This question already has answers here:
Javascript - Variable in function name, possible?
(5 answers)
Closed 8 years ago.
I have function name in a var,
var i = 2; // iteration
var fname = 'myFunction' + i; // looks like myFunction2()
now i want to assign this function on element's event. i.e.
var elem = document.getElementById('e');
elem.onclick = fname;
It doesn't work. JS take function name as 'fname()' not the string inside it 'myFunction2()'
A little help would be appriciated,
Thanks in advance.

You can do this
window['myFunction' + i]
or create a array/object of functions.
var i = 2; // iteration
var fname = 'myFunction' + i; // looks like myFunction2()
var elem = document.getElementById('e');
elem.onclick = window[fname];

Check these answers: Javascript - Variable in function name, possible?
and Use JavaScript variable as function name?
What you attempt is to assign a string (variable) on an event.

Related

Using id as variable in querySelectorAll() [duplicate]

This question already has answers here:
How do I concatenate a string with a variable?
(5 answers)
Closed 4 years ago.
I need to use an id as variable in querySelectorAll() as shown below.
var thismodal = "myModal";
var clicked_id,trueModalId;
function openModal(clicked_id) {
trueModalId = thismodal + clicked_id;
document.getElementById(trueModalId).style.display = "block";
// var thisSlides = "mySlides" + clicked_id;
if($('trueModalId').find('.modal-content').length) {
alert(trueModalId);
}
}
function showSlides(){
var slides = document.querySelectorAll('trueModalId >.modal-content > .mySlides');
}
How do I make this work?
Just like every variable and string concatenation in js works. You forgot the # as an indicator for id though
var trueModalId = "myModal";
var slides = document.querySelectorAll('#' + trueModalId + ' >.modal-content > .mySlides');

Dynamically Select Variable [duplicate]

This question already has answers here:
Access value of JavaScript variable by name?
(7 answers)
Closed 5 years ago.
I have 2 variables like so
var variable_1 = "foo";
var variable_2 = "bar";
I use a function to grab the value of a checkbox input and for each checkbox which is checked, I want to load the particular variable which depends on value of checkbox.
$("input:checked").each(function() {
$(div).append('variable_'+$(this).val());
}
So I'd concatenate the text 'variable_' with the value of each checkbox.
Thanks!
You can use eval to get any variable values dynamically.
var variable_1 = "foo";
var variable_2 = "bar";
$("input:checked").each(function() {
$(div).append(eval('variable_'+$(this).val()));
}
Note: it's not the best solution because eval has some security issues as well.
Because calling a variable or function from a user input is dangerous, and particularly if you are only using two different variables, you would be better off using a simple if statement.
This one is a ternary if:
var variable_1 = "foo";
var variable_2 = "bar";
$("input:checked").each(function() {
var isChecked = $(this).is(':checked');
var append = (isChecked) ? variable_1 : variable_2;
$(div).append(append);
}
Alternatively you could use a switch statement for multiple values.
If the variables are globals then you can use
var y = window["variable_" + x];
to read or
window["variable_" + x] = y;
to write to them dynamically.
Better practice however is to use an object to store them instead of using separate variables...
var data = { variable_1: null,
variable_2: null };
...
y = data["variable_" + x];
Javascript can also use eval to access dynamically variables, amazingly enough even local variables
function foo(s) {
var x = 12;
return eval(s);
}
console.log(foo("x"));
and even more amazingly this allows the dynamic creation of new local variables...
var y = 42;
function foo(s) {
var x = 1;
eval(s);
return y; // may be global y or a local y defined by code in s
}
foo("x") // returns 42
foo("var y = 99") // returns 99 (but global y is not changed!)
but these uses of eval should be considered more a bug than a feature and are best avoided (they also makes the code basically impossible to optimize or understand so "just don't do it"™).
Create object with properties and access that properties via obj['prop'] notation, see code below:
var myObj = {'variable_1': 'foo', 'variable_2': 'bar'};
$("input:checked").each(function() {
var dynamicVariableName = 'variable_' + $(this).val()
var dynamicVarValue = myObj[dynamicVariableName];
$(div).append(dynamicVar);
}
If your variables lives under window it's better to create new global object which contains that variable rather than keeping that variables as globals.

Using javascript, is there a way to pull the window's current URL parameters and store into a variable? [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Check url parameter using javascript
(3 answers)
Closed 9 years ago.
I'm aware of window.location.host and window.location.pathname, but is there anyway to pull the extra parameters of a link like this?
http://www.example.com/test?u=123
I would like to end up with a dynamic variable that is equal to "u123" but without the double quotes.
Thanks!
var oGetVars = {};
if (window.location.search.length > 1) {
for (var aItKey, nKeyId = 0, aCouples = window.location.search.substr(1).split("&"); nKeyId < aCouples.length; nKeyId++) {
aItKey = aCouples[nKeyId].split("=");
oGetVars[unescape(aItKey[0])] = aItKey.length > 1 ? unescape(aItKey[1]) : "";
}
}
// alert(oGetVars.yourVar);
window.location! MDN window.location
For a basic example of getting all the page parameters into a usable variable try this:
var pageParams = {};
if(location.search != ''){
var searchStr = location.search;
searchStr = searchStr.substr(1);
var searchStrArr = searchStr.split('&');
var pageParamPair, pageParamKey, pageParamValue;
for(var i=0;i<searchStrArr.length;i++){
pageParamPair = searchStrArr[i].split('=');
pageParamKey = pageParamPair[0];
pageParamValue = pageParamPair[1];
pageParams[pageParamKey] = pageParamValue;
}
}
thus in your case pageParams['u'] = "123"

create variable name function [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript dynamic variable name
I'm trying to create a function in javascript that has a name dependent on a variable.
For instance:
var myFuncName = 'somethingWicked';
function myFuncName(){console.log('wicked');};
somethingWicked(); // consoles 'wicked'
I can't seem to figure out a way to do it.... I tried to eval it, but then when I try and use the function at a later time it 'doesnt exist'.. or more exactly I get a ReferenceError that the function is undefined...
Any help would be appreciated.
You could assign your functions to an object and reference them like this:
var funcs = {};
var myFuncName = 'somethingWicked';
funcs[myFuncName] = function(){console.log('wicked');};
funcs.somethingWicked(); // consoles 'wicked'
Alternatively, you could keep them as globals, but you would still have to assign them through the window object:
var myFuncName = 'somethingWicked';
window[myFuncName] = function(){console.log('wicked');};
somethingWicked(); // consoles 'wicked'
var myFuncName = 'somethingWicked';
window[myFuncName] = function(){console.log('wicked');};
somethingWicked(); // consoles 'wicked'
Any time you have to create something that depends on a dynamic name for a variable you should be using a property of an object or an array member instead.
var myRelatedFunctions = {};
var myFuncName = 'somethingWicked';
myRelatedFunctions[myFuncName] = function (){console.log('wicked');};
myRelatedFunctions['somethingWicked']()

JavaScript - Using a variable to refer to a property name? [duplicate]

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 8 years ago.
I am creating my own object:
gridObject = new Object();
I am then using jquery to pull the contents of list item tags, which themselves are filled with tags that have specific class names:
<li row="1"><p class="department" rowitem="department">Photography</p>...</li>
I am pulling them using this code:
//make object from results
gridObject = new Object();
//get all the rows
var rowlist = $('li[row]');
for(var r=0; r<rowlist.length; r++) {
//make gridObject row element here
//get the row content
var thisrow = $(rowlist[r]).html();
//get all the p tags
var rowitems = $(thisrow + 'p.[rowitem]');
//get field name
for(var ri=0; ri<rowitems.length; ri++) {
if (r < 2) { //this is temporary just for testing
var fieldname = $(rowitems[ri]).attr('rowitem');
var fieldvalue = $(rowitems[ri]).html();
}
}
Ia m getting hung up passing this into my object. Two questions. Can an object property be made with a variable name, like so
griObject.fieldname = fieldvalue;
and can the objects have parent/child relationships such as:
gridObject.r.fieldname = fieldvalue;
in this case both r and fieldname would be variables. Or should I just be working associative arrays to achieve something similar?
This is in answer to a follow up question I posted below: "Is there a print_r equivalent in javascript" - you can use iterator, a bit more typing but does the trick:
//loop through search data
var it = Iterator(filteritems);
for(var pair in it) {
console.log("key:" + pair[0] + ", value:" + pair[1] + "\n");
}
If you want to use a variable property name, use subscript syntax:
var fieldname = 'test';
//These two lines are equivalent as long as fieldname is 'test':
gridObject[fieldname] = fieldvalue;
gridObject.test = fieldvalue

Categories

Resources