0

I have group of check-boxes and corresponding text-boxes with them. I can get each checkbox one by one, but how do I get the group of textboxes so I can validate them?

Here is my javascript code below:

function validate_orderform(proform) 
{           
var flag=0;
for (var i = 0; i < proform.chk.length; i++) {
   if (proform.chk[i].checked && proform.quant[i].value=="") {       
        flag=1;
   }
}

if(flag==1){
return false;
}

return true;
}

and my html code:

<td><input type="checkbox" id="chk1" name="chk"></td>
<td><input type="text" size="10" id="quant1" name="quant1"></td>...and so on
1
  • What do you have to check? if field is empty? if it's a number? Commented Nov 19, 2010 at 8:36

2 Answers 2

1

If name of textboxes are different then you can access all textboxes by

 var txtObjList = document.getElementsByTagName("input");
 for(var i=0; i < txtObjList.length; i++){
    if(txtObjList[i].getAttribute("type") == "text" && this.value != ""){
      // success for i+1 textbox
   }
 }

Or you can give common class name to all textboxes and then can access by

 var txtObjList = document.getElementsByClassName("classname");
 for(var i=0; i < txtObjList.length; i++){
    if(this.value != ""){
      // success for i+1 textbox
   }
 }

Remember by using javascript library such as jquery, prototype your work will be simpler.

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

Comments

0

There are a couple of methods you could use, you could use document.getElementsByTagName to retrieve all of the input elements, check their type etc... It works but it's slow and potentially expensive depending on how complex your form is.

If you have a group of checkboxes and each one has it's own text box then you could group them, so add a common name to each type, e.g.

Entry 1:
<input type="checkbox" id="chk1" name="chk"/>
<input type="text" id="quant1" name="quant"/>

Entry 2:
<input type="checkbox" id="chk2" name="chk"/>
<input type="text" id="quant2" name="quant"/>

Then you can use the document.getElementsByName method, so in this instance the following would retrieve a collection of 2 objects for you're text boxes:

var myTextBoxes = document.getElementsByName("quant");

1 Comment

Also you could optimize your for-loop a bit more by changing it to "for (var i = 0, j = proform.chk.length; i < j; i++) { ... }". That way you wont be evaluating the length of the collection each iteration.

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.