0

I have a signup form which is having some 12 fields. I want to validate data in those fields. First step is to check if any field is empty. One way of doing this is to get each field using Jquery and check if it is empty. I was planning to create a var array and check status of each field inside a loop using this code :

    var input = new Array();
    input[0]  =  $('.fullName')[0];
    input[1]  =  $('.emailID')[1];
    input[2]  =  $('.phno')[2];
    input[3]  =  $('.userName')[3];
    input[4]  =  $('.password')[4];
    input[5]  =  $('.batch')[5];
    input[6]  =  $('.nickname')[6]
    input[7]  =  $('.enrno')[7];
    input[8]  =  $('.dob')[8];
    input[9]  =  $('.fromCity')[9];
    input[10] =  $('.currcity')[10];
    input[11] =  $('.interests')[11];
    input[12] =  $('.currComp')[12];
    input[13] =  $('.currDesig')[13];

Now I have to run a loop to get the values and check if any field is blank. I am writing this code for checking

for(i=0;i<14;i++)
    if(input[i].val()=="")
    {
        // do my work
    }

But the problem is that the last 15 lines of code are pointing to actual HTML DOM element, so I can't use input[i].val() directly to access the value. Any way out?

2
  • 3
    Why the [0] part for each jquery selector, seems like you remove that and the problems gone. Commented Aug 8, 2014 at 14:48
  • You don't need to use indexing in the jQuery selectors. You actually don't even need to create an Array to achieve this. Check @adeneo answer. Commented Aug 8, 2014 at 14:49

1 Answer 1

3

You seriously need to just add a common class to the elements that needs validation, and then do

var is_valid = $('.validate_these').filter(function() {
                  return $.trim(this.value) === "";
               }).length === 0;

That gets all the elements with that class, and filters them based on wether or not the value is empty. If no empty elements where found, it's valid

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

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.