0

This is my html:

<form>
<input type='text' name='campo1' value='valor0'/>
<input type='text' name='campo2' value='valor1'/>
<input type='text' name='campo3' value='valor2'/>
<input type='text' name='campo4' value='valor3'/>
<input type='text' name='campo5' value='valor4'/>
<input type='text' name='campo6' value='valor5'/>
<input type="button" onclick="inpt();">
</form>

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.

<script type="text/javascript">
var tags_inpt = new Array();
var param = "";;
function inpt() {
tags_inpt=document.getElementsByTagName('input');
var i;
for (i=0; i<tags_inpt.length; i++) {
if ((tags_inpt[i].type=='text')&&(tags_inpt[i].name.match(/campo/))){
param += '"' +tags_inpt[i].value +'",';
}
}
alert(param + '"A"'); // this print -> "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);
}
</script>

When use param variable to dynamically pass arguments to funcion2(), I get undefined value.

What is the correct way to make this?

Thanks

2 Answers 2

2

Try this:

funcion2.apply(window, (param + ',"A"').split(",") );

See the DEMO

Sign up to request clarification or add additional context in comments.

Comments

1

Don't use string concatenation for this, that's prone to errors depending on your input. Use an array instead:

<script type="text/javascript">
function inpt() {
  var tags_inpt = document.getElementsByTagName('input');
  var matches = [];
  for (var i=0; i<tags_inpt.length; ++i) {
    if ((tags_inpt[i].type=='text') && (tags_inpt[i].name.match(/campo/))){
      matches.push(tags_inpt[i].value);
    }
  }
  matches.push('A');
  funcion2.apply(this, matches);
}

function funcion2(a,b,c,d,e,f,g) {
  var z = b;
  alert (z);
}
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.