tags:

views:

48

answers:

3

I am trying to put a variable into a dom string. I have various fields as such:

<input type="text" name="itemdesc1" />
<input type="text" name="itemdesc2" /> 

I want to loop through these to see if they are populated before submit. The only problem I have is that I cannot run them through a loop, because I need to put a variable into the DOM string. The variable is "i".

if (document.insertinv.itemdesc(variable_here).value == ''){
     // Code
}

Is there any specific way to do this? Preferably without adding id's to the fields.

Thanks!

+1  A: 

try

if ( document.getElementsByName("itemdesc"+i).value == '' ){
     //CODE
}
Treby
`.` is not the concatenation operator
Justin Johnson
Treby is likely a PHP programmer :) I find myself mixing up the syntax from time to time too :)
Jonathan Sampson
sorry man.. got carried away.. yah jonathan.. i am a php programmer
Treby
Nearly there but `getElementsByName` returns a list of matching elements, not a single element.
bobince
+1 following changes.
Jonathan Sampson
+2  A: 

You can use the bracket notation, also I would encourage you to access your form elements in the standard way, accessing the elements HTMLCollection (document.forms[x].elements[y]):

var element = document.forms[0].elements['itemdesc' + i]; 
         //or document.forms['formName']...
if (element.value == ''){
  // Code
}
CMS
+2  A: 

You'll need to concatenate the variable onto the dom-string:

var elems = document.getElementsByName('itemdesc'+i);
Jonathan Sampson