Click to See Complete Forum and Search --> : how to use a variable as a field name?


MarkNL
04-26-2003, 03:22 PM
I made this function:


function alertvalue(number){
alert(document.formname.number.value);
}


when i call the function: alertvalue("field6")
and i have <input name="field6" value="right"> somewhere in my document, it SHOULD alert "right"

BUT that doesnt work, it tries to alert the value of the field named "number" instead of "field6"

so how can i use the variable "number" in the field name?
something needs to be changed in "alert(document.formname.number.value);", but I dont know how to do it, could anyone help me plz?

Charles
04-26-2003, 03:29 PM
function alertvalue(number){
alert(document.formname[number].value);
}

MarkNL
04-27-2003, 03:42 AM
Your document.formname[number].value thing only works if i do alertvalue(0), or when i make 2 fields, alertvalue(1) works too.
But I want to use a string like alertvalue("field6"), and that doesnt work :(

Charles
04-27-2003, 05:14 AM
Did you try my method?

MarkNL
04-27-2003, 06:12 AM
Yes i tried both, and they dont work when i put something else than a number

Charles
04-27-2003, 06:24 AM
It works just fine for me, though. And in several different browsers.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Content-Script-Type" content="text/javascript">.

<script type="text/javascript">
<!--
function validateKing(control) {
alert (document.forms.king[control].value);
return false;
}
// -->
</script>

<form action="" name="king" onsubmit="return validateKing('tut')">
<div>
<input type="text" name="tut" value="Amonhoteph IV"><br>
<input type="submit">
<div>
</form>

MarkNL
04-27-2003, 11:51 AM
Charles is right, his code works. I have probally done something else wrong.

MarkNL
04-27-2003, 01:10 PM
ok i think i found the problem

but when i use

document.write('<a onclick="myfunction("a value");">something</a>');

then it gives an error, because i use " between 2 "s, is there a way i could do this?

Charles
04-27-2003, 01:41 PM
document.write ('<a href="#">Some Text</a>');
document.links[document.links-1].onclick = function () {alert ('Some Other Text')}

MarkNL
04-27-2003, 04:06 PM
that doesnt really work when i try it without anything else :confused:

but i think this topic can be closed,
i just use:

document.write('<a onclick=myfunction("a value");>something</a>');

I know its not a good solution, but it works..