0

I have a form with a bunch of text boxes named the same with a sequential number. ex. answer1, answer2, answer3 etc. I want to check to make sure a value is put in each field an easier way than putting a line of JS for each text box. Is there a way to build the field name dynamically? I've tried several things but keep getting syntax errors. The code is one of my attempts to do this.

function checktextboxes{
for (var x=1; x< 50, x++)
{
if (document.form1.answer'x'.value == null){
    alert ("error")
break}}}

Also, I may want use the routine later to check to see if the value of one text box is the same as another text box, so the solution would need to do more than check null.

2 Answers 2

2

Your syntax is incorrect.

document.form1.answer'x'.value == null

You cannot just put that string there. Use the [] notation like this:

document.form1['answer' + x].value == null

This will evaluate to:

document.form1['answer1'].value == null

etc. which is equal to

document.form1.answer1.value == null
Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

function checktextboxes() {
    for (var x=1; x< 50, x++) {
       if (document.form1["answer" + x].value == null) {
         alert ("error")
         break
       }
    }
}

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.