AlexandraNicodemus
AlexandraNicodemus

Reputation: 21

How to add textarea validation into a form using the existent jQuery code

This is my html (in which I just added textarea):

<form>
<div id="input_wrapper">
    <label for="name">Name:</label>
        <input type="text" name="name" value=""/>
        <label for="phone">Phone:</label>
        <input type="text" name="phone" value=""/>
        <label for="email">Email:</label>
        <input type="text" name="email" value="" />
        <label for="textbox">Comments:</label>
        <textarea name="textbox" rows=3 cols=30 ></textarea>

        <input type="submit" value="" />
    </div>
</form>

and this is the other part of the code:

 $('form').submit(function (e) {
    var flag = true;
            var inputs = $(this).find('input[type="text"]');

            inputs.each(function(){
                if ($(this).val() === ''){
                    //$(this).addClass('invalid');
                    $(this).prev().addClass('invalid');
                    if ($(this).next().is('span') === false){
                        $(this).after('<span>' + $(this).attr('name') + ' is required</span>');
                    }
                flag = false;
                }else{
                    $(this).removeClass('span');
                    $(this).prev().removeClass('invalid');
                    if ($(this).next().is('span')){
                        $(this).next().remove();
                    }
                }
            });
            if (flag === false) {
            e.preventDefault();
            }
});

I need to include my textarea in jquery and it must work the same way as input does.

Upvotes: 2

Views: 963

Answers (3)

kapa
kapa

Reputation: 78681

Simply add it into the selector:

var inputs = $(this).find('input[type="text"], textarea');

In a jQuery selector, you can list more than one item using a comma. It is called the Multiple Selector:

Selects the combined results of all the specified selectors.

Upvotes: 0

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

Just changing this one line should do the trick...

var inputs = $(this).find('input[type="text"], textarea');

Upvotes: 2

versvs
versvs

Reputation: 643

It may not be what you're after, but... isn't validation plugin an option?

More info: http://docs.jquery.com/Plugins/Validation

Upvotes: 1

Related Questions