Call a function specified in variable in javascript [duplicate] - javascript

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 7 years ago.
I have a input hidden type which specifies the function that needs to be called. How can I do it using Javascript/Jquery
<input type="hidden" name="extrafunction" id="extrafunction" value="edit_data_provider/DataProviderChange1" />
and in Javascript file
var fullfunctionName = $('#extrafunction').val();
var control_name = fullfunctionName.split('/')[0];
var function_name = fullfunctionName.split('/')[1];
if(control_name == client_control_name)
{
//The function call which is in function_name var should come here
}

You can use :
window[functionName](arguments);
Hope this helps.
var functionName="my_function";
function my_function(){
console.log('test from my_function');
}
window[functionName]();

Related

Replace function showing undefined in the console [duplicate]

This question already has answers here:
JS replace not working on string [duplicate]
(2 answers)
Closed 7 months ago.
So, I was trying to create e encryption app, the app should take the value of the input and use the replace function to change the letters to the words that I specified in the function trocaLetras, but it just returns undefined in the console log.
This is my code:
var botaoCriptografar = document.querySelector('#criptografar');
function trocaLetras(conteudoInput) {
conteudoInput.replace(/a/g, 'ai');
conteudoInput.replace(/e/g, 'enter');
conteudoInput.replace(/i/g, 'imes');
conteudoInput.replace(/o/g, 'ober');
conteudoInput.replace(/u/g, 'ufat');
}
botaoCriptografar.addEventListener('click', function(event){
event.preventDefault();
var texto = document.querySelector('#texto-para-coleta').value;
var textoAtualizado = trocaLetras(texto);
console.log(textoAtualizado);
});
<textarea id="texto-para-coleta"></textarea>
<button id="criptografar">Criptografar</button>
The replace function will actually not change the value in the variable, but instead returns a string with the replaced characters. So you must chain multiple calls of replace.
Also your function needs to return the result. So your function works if you change it to this:
function trocaLetras(conteudoInput) {
return conteudoInput.replace(/a/g, 'ai')
.replace(/e/g, 'enter')
.replace(/i/g, 'imes')
.replace(/o/g, 'ober')
.replace(/u/g, 'ufat');
}
two issues here
.replace doesn't change the original variable value. so if you do
let s = 'some';
s.replace('some', 'else');
console.log(s); // 'some'
so your function needs to reassign the value, or you can create a new one.
javascript function needs explicit returns, so if you don't return anything, it'll show up as undefined.
function trocaLetras(conteudoInput) {
conteudoInput = conteudoInput.replace(/a/g, 'ai');
conteudoInput = conteudoInput.replace(/e/g, 'enter');
conteudoInput = conteudoInput.replace(/i/g, 'imes');
conteudoInput = conteudoInput.replace(/o/g, 'ober');
conteudoInput = conteudoInput.replace(/u/g, 'ufat');
return conteudoInput;
}
const botaoCriptografar = document.getElementById('button');
botaoCriptografar.addEventListener('click', function(event){
event.preventDefault();
var texto = document.querySelector('#texto-para-coleta').value;
var textoAtualizado = trocaLetras(texto);
console.log(textoAtualizado);
});
<button id='button'>Encrypt</button>
<input id="texto-para-coleta" />

How can i change the variable name in javascript? [duplicate]

This question already has answers here:
Use dynamic variable names in JavaScript
(19 answers)
Closed last year.
I have some js code like this:
var parameter0 = 12345;
var parameter1 = 54321;
var parameter2 = 33333;
var parameter3 = 99990;
function selectValue(number) {
alert(parameter+number);
}
selectValue(2);
Here is a fiddle - https://jsfiddle.net/frwd2qLg/
This code will not work, because, for example, for number = 2, it will not show 33333, but will be undefined. Any workaround?
As people said in your comments, you could use an array or an object to do this task. But answering your question you culd use an eval to access the variable name.
var parameter0 = 12345;
var parameter1 = 54321;
var parameter2 = 33333;
var parameter3 = 99990;
function selectValue(number) {
alert(eval("parameter"+number));
}
selectValue(2);

Using input value in the JavaScript function name [duplicate]

This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 3 years ago.
I am trying to create JavaScript function dynamically and want to use input value as function name.
I tried:
function calculate(){
var dur = document.getElementById('duration').value; //example value: 1
var sum = document.getElementById('sum_insured2').value; //example value: 1000
`'show_d'+dur+'_sum'+sum();`
}
I want like this:
`show_d1_sum1000();`
I am not getting the output what I want.
You cannot dynamically call a function based on the value of variables in the manner you're attempting.
One workaround would be to put the function in an object and then use bracket notation to invoke the property, something like this:
var funcs = {
'show_d1_sum1000': function() { // 1 | 1000
console.log('foo bar');
}
}
var dur = document.getElementById('duration').value;
var sum = document.getElementById('sum_insured2').value;
funcs[`show_d${dur}_sum${sum}`]();
<input type="text" value="1" id="duration" />
<input type="text" value="1000" id="sum_insured2" />
That being said, this is not a good pattern to follow. In your case I'd suggest executing a single statically defined function which handles the values of the inputs, whatever they may be.
What about trying this:
console.log('show_d' + dur.toString() + '_sum' + sum.toString());
In order to create a method dynamically by this name try this:
var name = 'show_d' + dur.toString() + '_sum' + sum.toString();
var f = new Function('name', 'return alert("hello world");');
and call the method using f()
If you have already a method in your window with the same name then try accessing it like this:
window[name](anyArguments);

JSON parsing syntax impossible [duplicate]

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 8 years ago.
I need to rotate a DIV, but that is not the problem I am facing, it is JSON parsing,
I want to be able to get the proper attr value from the variable rotateAttrSet but I want to get it according to the browser type
I can do var rotateAttr = rSET.FF;, but I can't do var rotateAttr = rSET.brwShort;
Is there a way to make this work?
again, I am not looking for ways to rotate the DIV, I just want to know if there is a way to get the JSON work by a variable (like .brwShort below)
Thanks
<script>
var rotateAttrSet = '{"IE":"-ms-transform","FF":"-moz-transform","CR":"-webkit-transform","SF":"-webkit-transform","OP":"-o-transform","WC3":"transform"}';
function rotator(o)
{
var o = $(o);
var angle = 0;
var rSET = parseJSON(rotateAttrSet);
var brwShort = "FF";//getBrowser().split(";")[2];
var rotateAttr = rSET.brwShort;
//alert(rotateAttr);
//o.removeAttr("onClick");
setInterval(function(){
angle++;
if(angle == 360) angle = 0;
o.text(angle);
o.css(rotateAttr, "rotate("+angle+"deg)");
}, 10);
}
function parseJSON(s)
{
return eval('('+s+')');
}
</script>
You need to use the browser short as a key as follows:
var brwShort = "FF";//getBrowser().split(";")[2];
var rotateAttr = rSET[brwShort];
Otherwise, it is actually looking for a property on the object with a key of "brwShort", which doesn't exist on your object.

Javascript / jquery - like PHPs $_GET [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 9 years ago.
I have a variable set in my url:
http://mydomain.com?myvar=1
Now I need to check this when the page loads. I would normally do this in PHP but I need to use some jQuery. What I want to do is something like:
$(document).ready(function() {
var somevar = $GET['myvar'];
if (somevar = '1') {
$('#someDiv').hide();
}
});
How can I do this if its at all posible?
Here's a function that will do that:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}

Categories