2

simple javascript but can't seem to get it to work.

var number = 5;
var netiteration = "net"+number;  // makes netiteration now equal net5

var formvalue = document.forms.myformname.netiteration.value;

why doesn't this get the value of the form field with the name/id of "net5", in the form "myformname"?

also, I'm working from a 10 year old javascript book, so maybe the syntax has changed?

thanks

1
  • 1
    did you try document.getElementsByName(netiteration)[0].value Commented May 30, 2013 at 12:07

3 Answers 3

6

Try:

var number = 5;
var netiteration = "net"+number;  // makes netiteration now equal net5

var formvalue = document.forms.myformname[netiteration].value;

Your original code was looking for a field called "netiteration" but you want the field that has a name equal to the evaluated value of netiteration.

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

Comments

0

This will not work as netiteration is a variable and you cannot use variable name within the DOM structure of the HTML.

something like following should work....

var form_elements = document.forms.myformname.getAllChildren();
var net_elements = new Array[10];
for(var i=0;i<form_elements.length;i++)
{
   var name = form_elements[i].name;
   if(name.indexOf('net') != -1)
    net_elements[i] = form_elements[i];
}

now, the arraynet_elements has all the elements with the name 'net' in it...

hopes this solves your problem...

Comments

0

Came across this and thought I'd enhance it with some extra info in case someone finds it useful.

If you are using id in your form fields, you can reference that way also:

<input type='text' id='myfield1' onclick="Example(1)">
<input type='text' id='myfield2' onclick="Example(2)">

then in your Javascript you reference the field with a variable by:

function Example(myvar){
    var myvalue=document.getElementById('myfield'+myvar);   
    console.log('The value is '+myvalue);
}

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.