views:

161

answers:

1

I have a form, that has about 10 text entries (user, address, email etc;) and about 50+ entries that are quantity entries (users select 2x of this item, 5x of this item).

Now I inherited this form from someone else (now its my duty to keep it up to date, when the customer requests it).

I don't want to re-write it all, but I would like to add validation for the quantity fields.

Now the quantity fields are all named different things (b1,c55,d,12)

Basically I would like to write a script (but don't know how to search for this, or accomplish this) JS side, that would ignore the tags I know (user, address, email etc;) but check if the others are numbers (either empty - not selected, or 1-99)

+2  A: 

Apply a class to the elements (my code uses a class check) like so:

<input type="text" name="b1" class="check" />

and the following jQuery code, which will only check those elements with the check class.

$('#myformid').submit(function(){
 $(':input.check').each(function(){
  field = $(this);
  valInt = parseInt(field.val()); // value as an integer

  if (isNaN(valInt) || (valInt < 1 || valInt > 99)) // displays an error if the val is < 1 or > 99
       alert('Error in the field ' + field.attr('name') + ': must be number from 1-99'); // change this to whatever you want the form to do if there's an error
 });
});

Basically what this does is the following: when the form is submitted, it goes through every field you'd like it to (denoted :input.class to catch each field with the correct class) and checks if it's (a) a number, and (b) less than 1 or greater than 99. If it's a number and is outside the range, it alerts the user of an error. You can change the alert() notification to whatever error management you'd like your form to have.

Josh Leitzel
@Josh Leitzel: However, if I don't want to define each name? I have 50+ entries, and I don't care for their name, I just want to make sure that they are 1-99, or empty. As these values change on a weekly basis, I don't want to keep updating this script. So I would need jQuery to go through all the form elements? How would I accomplish that? What I picture is loop through like an array, and ignore the 'known' (email, first, last, etc). Appologies if I wasn't too clear.
Jakub
Sorry about that. You can use a CSS class to easily accomplish what you'd like to do. I've edited my answer accordingly.
Josh Leitzel
ahh, smart. I didn't even think to group by class. Thank you very much!
Jakub