Abdus Sattar Bhuiyan
Abdus Sattar Bhuiyan

Reputation: 3074

each inside this object using jquery

I have two form having same class name. I want to check all required fields inside clicked from. HTML:

   <form action="#" id="form_sample_3" class="form-horizontal normalForm1">
            <div class="form-group c_name_container">
                <div class="col-md-12">
                    <div class="input-group">
                        <span class="input-group-addon">
                            <i class="fa fa-envelope"></i>
                        </span>
                        <input type="text" id="c_name"  class="required" placeholder="Type your Name here"/>
                    </div>
                </div>
            </div>
            <div class="form-group c_email_container">
                <div class="col-md-12">
                    <div class="input-group">
                        <span class="input-group-addon">
                            <i class="fa fa-envelope"></i>
                        </span>
                        <input type="email"  id="c_email" class="required" placeholder="Type your Email Address">
                    </div>
                </div>
            </div>
            <div class="form-actions">
                <div class="row">
                    <div class="col-md-offset-3 col-md-9">
                        <button type="button" id="start_chat" class="btn green">Start Chat</button>
                    </div>
                </div>
            </div>
        </form>

now,

$(document).on("click", ".normalForm button[type='submit']", function () {
  // this will refer clicked form having class `normalForm`
  // Here i want to looping for all .required class.
  $('.required').each(function(){
         //  it works fine. but it looping also others .required class of other form in same page. How can I looping only inside my clicked form? 


       });
});

Upvotes: 2

Views: 189

Answers (3)

A. Wolff
A. Wolff

Reputation: 74420

You should bind submit event of the form instead as a form can be submitted without clicking submit button. Then simply loop over all .required elements inside this form:

$(document).on('submit', '.normalForm', function () {
    $(this).find('.required').each(function () {
        /*...*/
    });
});

Upvotes: 2

Alnitak
Alnitak

Reputation: 339806

I would use:

$(this).closest('form').find('.required').each(...)

since this will be the clicked button, not the form itself, and this.form is HTML5-only.

Upvotes: 1

haim770
haim770

Reputation: 49095

Try this:

$('.required', this.form).each(function() {
    ...
};

Upvotes: 1

Related Questions