2

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!

3 Answers 3

3

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
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

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

Comments

1

try

if ( document.getElementsByName("itemdesc"+i).value == '' ){
     //CODE
}

4 Comments

. is not the concatenation operator
Treby is likely a PHP programmer :) I find myself mixing up the syntax from time to time too :)
sorry man.. got carried away.. yah jonathan.. i am a php programmer
Nearly there but getElementsByName returns a list of matching elements, not a single element.

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.