Pass generated string as variables in javascript function-Collection of common programming errors
This is my html:
I created a function to make a string and pass it to another function The string contain all values for input text with match string ‘campos’ in the input name.
var tags_inpt = new Array();
var param = "";;
function inpt() {
tags_inpt=document.getElementsByTagName('input');
var i;
for (i=0; i "valor0","valor1","valor2","valor3","valor4","valor5","A" OK!!
// call funcion2()
funcion2("valor0","valor1","valor2","valor3","valor4","valor5","A"); // this result in valor1 in funcion2() OK!!
funcion2(param + '"A"'); // this return 'undefined' --> BAD
}
function funcion2(a,b,c,d,e,f,g){
var z = b;
alert (z);
}
When use param variable to dynamically pass arguments to funcion2()
, I get undefined value.
What is the correct way to make this?
Thanks
-
Try this:
funcion2.apply(window, (param + ',"A"').split(",") );
See the DEMO
-
Don’t use string concatenation for this, that’s prone to errors depending on your input. Use an array instead:
function inpt() { var tags_inpt = document.getElementsByTagName('input'); var matches = []; for (var i=0; i
Originally posted 2013-11-09 19:41:57.