Jason Chen Jason Chen - 5 months ago 9
Javascript Question

Selecting specific element within a div?

I am building a contact form, and I am having problems with jQuery. I want to select specific input fields that have an error and apply the class

err
. Unfortunately, my code selects all inputs when there is an error. I am having trouble identifying which part of my logic is wrong.

$('#send_mail').click(function(){
$("#contact_body").find('label').each(function(){
var contact_label = $('input[required=true], textarea[required=true]');
var label_check = $(this).find(contact_label);
$(contact_label).removeClass('err');
if (!$.trim($(label_check).val())){
$(contact_label).addClass('err');
}
});
});


The order of my HTML goes something like so:

#contact_body
<label>
<input>
</label>

Answer

This selects all input and textarea elements:

var contact_label = $('input[required=true], textarea[required=true]');

Instead, you should restrict it to the elements within the label:

var contact_label = $(this).find('input[required=true], textarea[required=true]');

Note that $(contact_label) and contact_label are equivalent, as well as $(label_check) and label_check.

Also, you can use the state parameter of toggleClass() to simplify this:

contact_label.removeClass('err');
if (!$.trim(label_check.val())){
  contact_label.addClass('err');
}

… to this:

contact_label.toggleClass('err', !$.trim(label_check.val()));

Here's the updated event:

$('#send_mail').click(function(){
    $("#contact_body").find('label').each(function(){
        var contact_label = $(this).find('input[required=true], textarea[required=true]'); 
        var label_check = $(this).find(contact_label);

        contact_label.toggleClass('err', !$.trim(label_check.val()));
    });
});
Comments