Javascript check X number of fields in HTML form

I have a form that contains about 10 text entries (user, address, email, etc.); and about 50+ records which represent the number of records (users select 2x of this item, 5x of this item).

I have now inherited this form from someone else (it is now her responsibility to keep it updated when a client requests it).

I don't want to rewrite the whole thing, but I would like to add confirmation for the quantity fields.

Quantity fields are now denoted by different things (b1, c55, d, 12)

Basically, I would like to write a script (but don't know how to look for it or execute this) JS side that ignores the tags I know (user, address, email, etc.), but check if the rest digits (either empty - not selected, or 1-99)

+2


source to share


1 answer


Apply class

to elements (my code uses a class check

) like this:

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

and the following jQuery code that will only check those elements with a class check

.



$('#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 an error
    });
});

      

Basically, this is done like this: when the form is submitted, it goes through each field you would like (denoted :input.class

to catch each field with the correct class) and checks if it is (a) a number and (b) less than 1 or greater than 99. If this number is out of range, it alerts the user to the error. You can change the notification alert()

to whatever error management is required for your form.

+2


source







All Articles