简体   繁体   中英

Using a variable in a DOM string

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!

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
}

您需要将变量连接到dom-string上:

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

try

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM