0

get form element by using local variable in javascript function.
I need something like this..

function validateTxnProperties()
    for (i = 1; i < 37; i++) {
        if(checkMaxLength(document.formCollection.otherDocument<%=i%>Comments)){
            return false;
        }
    }
}

I need to replace below code with for loop.

if(checkMaxLength(document.formCollection.otherDocument1Comments)){
    return false;
}
if(checkMaxLength(document.formCollection.otherDocument2Comments)){
    return false;
}
......
if(checkMaxLength(document.formCollection.otherDocument36Comments)){
    return false;
}

Please update the question if i use wrong terms.

3
  • 1
    You can use bracket notation document.formCollection["otherDocument"+i+"Comments"] Commented Oct 14, 2017 at 7:12
  • @MarkE Thanks... Its working... Please can you explain how its work.. Is Form in jsp save as array? Commented Oct 14, 2017 at 7:27
  • 1
    You were using jsp notation inside js code. Also in JS you can access a property of an object both by dot notation or bracket notation, this does not mean that it is an array, is just another way to access the properties. It was the way to go in this situation since you can manipulate the property name like a string. If you wanna know more about accessing object properties please read Property accessors Commented Oct 14, 2017 at 7:35

1 Answer 1

1

@Mark E is correct, bracket notation is probably the way to go in this situation, but the for loop variable i needs to be declared somewhere, thus the var keyword in the loop, finally you want to put the condition you want to test in another function so that the loop doesn't terminate after the first return false;:

function condition(variable){
  if (checkMaxLength(document.formCollection["otherDocument" + variable + "Comments"])) {
     return false;
  } 
}

for (var i = 0; i < 37; i++) {
  condition(i);
}

Unless you do want the loop to terminate after the first return false* if so structure it like this:

for (var i = 0; i < 37; i++) {
  if (checkMaxLength(document.formCollection["otherDocument" + variable + "Comments"])) {
     return false;
  } 
}

If you wish for me to elaborate please do not hesitate to ask.

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

1 Comment

Good call on declaring i with var. Although it would work without doing it, you would be making i a global variable by using it without declaring, which is a bad practice.

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.