Using input value in the JavaScript function name [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 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);

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" />

use a passed val in js

I need to pass a value from html and use it to find a var in my Js, so according to the value in theId on my html I could use the var in my js. How can I do that?
HTML
<input id="Waist" type="checkbox" onchange="getToWork(this.id)" >Waist
<script> tag on HTML
function getToWork(theId){
usedCheckBox(theId);
}
myJs.js
function usedCheckBox(theId){
var temp1 = theId.name; - will be undefined
var temp2 = Waist.name; - will work
}
var Waist = {name:"bob",age:"17"}
The problem with your code is, you are not using document.getElementById as below:
JS:
document.getElementById("Waist").addEventListener("change",function(evt){
getToWork(this.id);
})
function getToWork(theId){
usedCheckBox(theId);
}
function usedCheckBox(theId){
console.log(theId);
console.log(Waist);
var temp1 = document.getElementById("Waist").val; // will return Waist
var temp2 = Waist.val(); // generate error, don't know what you want
}
var Waist = "change today!"
Fiddle:
https://jsfiddle.net/xLvzah8w/1/
I understood your question now and for that you should create one parent object as shown:
function usedCheckBox(theId){
var temp1 = parent[theId].name; // will return bob
console.log(temp1);
var temp2 = parent.Waist.name; // will return bob
console.log(temp2);
}
var parent = {
Waist : {name:"bob",age:"17"}
}
The reason why your code doesn't work is because you are trying to access property of a string. 'theId' is a string with value 'Waist' where Waist is an object so error occurs.
Updated fiddle: https://jsfiddle.net/xLvzah8w/2/
The correct way to proceed with this is:
In place of var temp1 = theId.val();
Use document.getElementById(theId).value
When you do: theId.val(), it makes sense that it's undefined. Calling getToWork(this.id) is sending a string, not an HTML element. Therefore calling .val() on a string is undefined.
If you're trying to get the text value stored in the checkbox element that was pressed, you need to change to ...
function getToWork(arg) {
console.log(document.getElementById(arg).value);
}
<input id="Waist" type="checkbox" value="INPUT_BOX" onchange="getToWork(this.id)"> Waist
You should avoid using the onclick attribute and rather listen for the event "js side" (addEventListener/attachEvent).
In the context of those eventhandlers, this generally represents the element the event listener has been attached to:
document.getElementById("Waist").addEventListener("change",getToWork);
function getToWork(){
usedCheckBox(this);
}
function usedCheckBox(elem){
var value = elem.value ;
}

Call a function specified in variable in javascript [duplicate]

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]();

Concatenate variable with a string to define another variable

I have a variable in a JavaScript
say like this
var divId = 2;
now I want to define some variable which will be like this
var day_2_0 = $("#rules_" + divId + "_offer_number").val();
but I dont want to define var day_2_0 straightforward.
I want something like this, if at all possible
var day = "day_"+divID+"_0";
so that var (var day) => var day_2_0;
Is anything like this possible in JavaScript?
NOTE: its something equivalent to this php snippet
$offer = "offer1";
$$offer then means $offer1
so if we write echo $$offer; then it means echo $offer1;
To my knowledge there are 2 ways you can do it:
1.eval (maybe avoid this one), i.e.
eval('var day_' + variableHere);
2.use an object
var someThing = {};
someThing['day_' + variableHere];
// then get the value by
someThing.day_variableValue;
Google eval for a million opinions on its use

jQuery val() Issue

I am using .val() to set the values in HTML. My code is like this:
function first(){
var a=1;
$("#pg_textbox").val(a);
}
Now this code sets vales in my hidden HTML id 'pg_textbox':
<input type="hidden" id="paging_textbox">
On the second function call, it is like this:
function secound(){
var b=2;
$("#pg_textbox").val(b);
}
Now when I use:
$("#pg_textbox").val();
to get the value of '#pg_textbox' i am getting output is
2
It is replacing the values. I want my output like:
1,2
How can I get this output without replacing the value?
Thanks.
When you call .val(b), you do reset the entire value of the textbox. Calling .val() will only retreive what's in the textbox, it has no recollection of past values.
You'll need to update your setter:
$('#pg_textbox').val( $('#pg_textbox').val() + ',' + b);
Try this code
var b=1;
var old_val=$("#pg_textbox").val();
$("#pg_textbox").val(old_val+" ,"+b);
You mean you're adding values to the input type, and don't want them to be replaced?
Well here's what you need to do then.
You need to make another hidden input type which will store the sum.
<input type="hidden" id="backup"/>
function first(){
var a=1;
$("#pg_textbox").val(a);
$("#backup").val(a);
}
function second(){ // Your second function
var b=1;
var sum = $("#backup").val()+b;
var old_val = $("#pg_textbox").val();
$("#pg_textbox").val(old_val+','+sum);
}
Also, you can continue this series with third, fourth, and so on...
This is what you're after.
var a = 1,
b = 2;
$("#pg_textbox").val(a + ', ' + b);
Although my code is technically correct, I can't imagine any practical application for it. Since you want to output some comma-separated values, it might be wiser to enter your values in an array, e.g.,
var yourValues = [1,2],
output = yourValues.toString();
$('#pg_textbox').val(output);​
Check if there's a value already, if there is, concatenate the values...
var newVal = 2;
var prevVal = $("#pg_textbox").val();
if (prevVal == '')
{
$("#pg_textbox").val(newVal);
}
else
{
$("#pg_textbox").val(prevVal + ',' + newVal);
}
Update this:
var b=2;
$('#pg_textbox').val( $('#pg_textbox').val() + ',' + b);

Categories