Anup
Anup

Reputation: 9738

How to Iterate to all Textboxes for Validation

I have dynamic Textboxes on my webpage around 50 Textboxes.

User can Set Order No. in these Textboxes. I have to ensure that only 3 Order No's can be set & no duplicate entries. So User can enter only 1, 2 & 3 in overall textboxes. If he enters 4 somewhere, he should get an error. Rest of the Textboxes have 0 as default value.

How to iterate to all textboxes for checking value not greater than 4 & no duplicate entries & no textbox empty?

Upvotes: 0

Views: 40

Answers (1)

Amir Popovich
Amir Popovich

Reputation: 29836

I'm pretty sure there are more elegant ways to do this, but here's the "straight forward" way:

function validateTextBoxes() {
    var values = [];
    var isError = false;
    var atLeastOneFilled = false;

    $('input[type=text]').each(function (idx, elem) {
        var val = $(elem).val();

        if (isNaN(val)) {
            isError = true; // input is not a number
        } else // a number
        {
            var intVal = Number(val);
            if (!isInt(intVal)) {
                isError = true; // not an interger
            } else {
                if (intVal !== 0) // default
                {
                    atLeastOneFilled = true;

                    if (intVal > 3 || intVal < 0) {
                        isError = true; // not in range
                    } else if (values.indexOf(intVal) > -1) {
                        isError = true; // duplicate
                    } else {
                        values.push(intVal);
                    }
                }
            }
        }
    });

    return atLeastOneFilled && !isError;
}

function isInt(n) {
    return n % 1 === 0;
}

JSFIDDLE.

Upvotes: 1

Related Questions