Call a javascript function dynamically - javascript

I have some functions defined inside a array like this.
checkInputType : function(sel){
alert($(sel).prop('type'));
},
checkSelect : function(el){
.......
},
.....
And I can call it like this options.checkInput($(this));. This is working.
Now I want to call any of those defined functions dynamically. So I have this array with the function names in it.
var elmType2Func = {'input' : 'checkInput', 'select' : 'checkSelect', 'textarea' : 'checkTextarea'};
Now looping through all elements inside a form I want to call the right function for each element(elmType2Func array with element as a key and function name as a value).
var element = $(this).prop('tagName').toLowerCase();
I cannot call like this - options.elmType2Func[element]($(this));
I know this is not the right way to call this function. Can anybody help me with this.

You need to store functions, not their names:
var elmType2Func = {'input' : checkInput, 'select' : checkSelect, 'textarea' : checkTextarea};
http://jsfiddle.net/hmb25/
If the functions are already members of some object, like:
var options = {
checkInput: function() {...},
checkSelect: function() {...},
}
then you can keep strings in elmType2Func:
var elmType2Func = {'input' : 'checkInput', 'select' : 'checkSelect', 'textarea' : 'checkTextarea'};
and use double indirection to refer to them:
var tag = $(this).prop('tagName').toLowerCase();
var fun = options[elmType2Func[tag]];
gives you a reference to the function.

Rather than putting a string for the name put the function
var elmType2Func = {
'input' : checkInput,
'select' : checkSelect,
'textarea' : checkTextarea,
'submit' : function (arg) { ... }
};

options.elmType2Func[element]($(this));
That is accessing the property with the literal name elmType2Func on the object - you want to use bracket notation here as well:
options[elmType2Func[element]]($(this));
Alternatively, you might not use elmType2Func as a property name lookup table, but to look up the functions directly:
var elmType2Func = {
'input' : options.checkInput,
'select' : options.checkSelect,
'textarea' : options.checkTextarea
};
elmType2Func[element]($(this));

Related

Store object inside object and update

I am trying to store an array inside and object like this:
var fieldData = {
checkedItem: {
fieldID : “1234”,
SelectedFields : []
}
checkedItem: {
fieldID : “12345”,
SelectedFields : []
}
}
I then want to also replace all selected fields to this object at a later stage.
I am a newbie to this so not sure how it would be done, I have tried everything I can think of!
The later changes to the object will referenced by fieldID.
I have tried stuff like:
fieldData["fieldID"] = selectedFieldSeq;
fieldData[selectedFieldSeq]["SelectedFields"] = $('#Tree').jqxTree('getCheckedItems');
$('#Tree').jqxTree('getCheckedItems');
returns an array of checked items on my tree.
This should do it:
'fieldID = $('#Tree').jqxTree('getCheckedItems');'
'fieldData.SelectedFields = fieldID'
There is a problem with this line :
fieldData[selectedFieldSeq]["SelectedFields"]
fieldData[selectedFieldSeq] is not defined, so it's return undefined
You need to initialize it before using it :
if (!fieldData[selectedFieldSeq]) {
fieldData[selectedFieldSeq] = {
SelectedFields : []
};
}
After, you can assign some value to SelectedFields.
Or did you want to simply do this : fieldData.SelectedFields = ...; ?

Access js object using variable

I'm not sure if I'm correct with topic title, so sorry about that.
I've got JS object '_buildings', which structure looks like this:
_buildings : {
laboratory : {
exist : false,
value : 1000,
},
office : {
exist : false,
value : 500,
},
}
Is it possible to access object somehow using this method:
var chain = 'laboratory'; //it could be 'office' or any other building name
var value = _buildings.chain.value;
Point is, I need to access object param while using variable in chain. Is it possible?
JSFiddle: http://jsfiddle.net/3k5anjjj/
yes, use square bracket notation
var x = _buildings[chain].value;
Updated fiddle: http://jsfiddle.net/3k5anjjj/1/

Access JSON values from variable

The click handler is accessing a data attribute on the element and setting a variable based on what is it, in this case 'option1'. I want to use the name of this variable to access a JSON object. But in the example it's returning 'undefined', as if it's looking for an array called 'thisOption'. How can I use this data attribute to bring back the correct JSON content?
// Note: thisOption returns "option1", which is correct.
jq = jQuery;
// Pass info
jq('.button').click( function() {
var thisOption = jq(this).data('name');
jq('#subscriptions .price').text(thisOption.monthly);
});
var option1 = {
"name" : "Super Pack",
"monthly" : "€10",
"yearly" : "€100",
"gift" : "Free €20 voucher"
};
If option1 is in the global scope then you can access it via the window object with a dynamic key:
jq('#subscriptions .price').text(window[thisOption].monthly);
The [] notation allows you to use variable property or key names.
You can access the option1 like below
jq('#subscriptions .price').text(window[thisOption].monthly);
Because option1 is in global scope, you can access it like window.option1. When option1 is a value of some variable, then you should access like window[thisOption]
I made some structure so we can see it clearly, you can also check it in jsfiddle.net
Heres the url: http://jsfiddle.net/8hTrr/3/
HTML
test
<div id="subscriptions">
<p class="price"></p>
</div>
JS
var option1 = {
"name" : "Super Pack",
"monthly" : "€10",
"yearly" : "€100",
"gift" : "Free €20 voucher"
};
jq = jQuery;
// Pass info
jq('.button').click( function() {
var thisOption = jq(this).data('option');
jq('#subscriptions .price').text(option1[thisOption]);
});

jQuery - Show variable, not text string

I have a variable being set as the .html(); of a <div />
The variable is the name of another variable. I want it to display the contents of the other variable, however it simply displays the name of the other variable.
How can I force it to show the variable contents rather than just a literal text string?
var clothing = 'dogeshop cryptoshop doge_clothing fyrstikken the_molly_machine peace_and_love moolah_market shibe_swag undieguys urban_graff kravshop got_doge mean_elephant the_dogedoor_store';
setInterval( function() {
var term = $("input").val();
$("#results").html(term);
}, 100);
When the user types 'clothing' into $("input"); the contents of the 'clothing' variable should be displayed in the $("#results"); <div />. Instead it just says 'clothing'.
Another way is to use object properties, like this
var obj = {};
obj.clothing = 'dogeshop cryptoshop doge_clothing fyrstikken the_molly_machine peace_and_love moolah_market shibe_swag undieguys urban_graff kravshop got_doge mean_elephant the_dogedoor_store';
setInterval( function() {
var term = $("input").val();
$("#results").html(obj[term]);
}, 100);
Here's the fiddle: http://jsfiddle.net/ZL7EQ/
The only way I know how to solve this is using eval:
$("#results").html(eval(term))
But you really shouldn't want to do that. :)
Use a dictionary.
// store strings in an object so you can look them up by key
var dict = {
clothing: 'dogeshop ...',
anotherKey: '...'
};
// update the result when the input changes
$('input').on('change', function() {
var result = dict[this.value]; // make sure the key exists
if (result) {
$('#results').val(result); // update the results
}
});
I use to make this mistake myself when working with jQuery.
Try instead:
$("#results").text(term);
Not sure what you have the interval for. You could just change the #results with a change event.

Using variables and functions in an object literal

I am trying to get the ckeip jquery plugin to parse the id of my textarea to my php file.
The plugin is activated by the class name of my textarea:
$('.ckeip_edit').ckeip({
And then data is passed to my php file with an object literal:
data: {
name1 : 'value1',
name2 : 'value2'
},
I need to use the id attribute of my textarea in one of these so tried:
data: {
name : 'value',
id : function(){this.getAttribute("id")}
},
But this doesn't seem to work.
Can I use variables in an object literal?
In this case you want a .each() and use this where needed inside to get an attribute from the current element for usage, like this:
$('.ckeip_edit').each(function() {
$(this).ckeip({
data: {
name : 'value',
id : this.id
},
//options...
});
});
That won't work because this refers to the data object. You need to save the jQuery object so you can use it inside the object later.
Try something like:
var textarea = $('.ckeip_edit');
textarea.ckeip({
data: {
name : 'value',
id : textarea[0].id;
}
});

Categories

Resources