What script error do you receive? Try placing the myname variable names in another variable before setting the value.
binoj_daniel
Practically a Master Poster
645 posts since Dec 2006
Reputation Points: 25
Solved Threads: 18
Or something like this. Works in IE, FF and Opera.
<html>
<head>
<script type='text/javascript'>
var CONST = 'myname';
function doSomething(frm)
{
for(var i = 1; i < 4; ++i)
{
var txt = CONST + i;
document.frm[txt].value = 'Test';
}
}
</script>
</head>
<body>
<form name="frm">
<input type = 'text' name = 'myname1' />
<input type = 'text' name = 'myname2' />
<input type = 'text' name = 'myname3' />
<input type = 'button' onclick = 'doSomething(this.form);' value = 'Do' />
</form>
</body>
</html>
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
I'm surprised no-one thought of:
var textBoxArray = document.getElementsByTagName("input");
for(var i = 0; i < textBoxArray.length; ++i)
{
if(textBoxArray[i].type == "text")
{
textBoxArray[i].value = "test";
}
}
All previous solutions rely on:
a. Knowing how many inputs there are.
b. Knowing the naming convention.
Shoot me down if you like but to me they are code smells.
hollystyles
Veteran Poster
1,182 posts since Feb 2005
Reputation Points: 262
Solved Threads: 68
Then that is best passed as a parameter IMO.
Just offering a more loosley coupled solution for the benefit of the thread that's all.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script type="text/javascript">
function setText(txtID, txtValue)
{
var textBoxArray = document.getElementsByTagName("input");
for(var i = 0; i < textBoxArray.length; ++i)
{
if(textBoxArray[i].type == "text" && textBoxArray[i].id.substring(0, txtID.length) == txtID)
{
textBoxArray[i].value = txtValue;
}
}
}
</script>
</head>
<body>
<input type="text" id="myname1" />
<input type="text" id="myname2" />
<input type="text" id="myname3" />
<input type="button" onclick="setText('myname', 'test');" value = 'Go' />
</body>
</html>
hollystyles
Veteran Poster
1,182 posts since Feb 2005
Reputation Points: 262
Solved Threads: 68