Get the correct label of an empty input

2019-09-06 19:14发布

问题:

Friends,

I have a form as below;

<form method="post" id="contact_form" action="">
<label for="name">Name</label>
<input type="text" name="name"  id="name" />

<label for="email">Email</label>
<input type="text" name="email" id="email" />

<label for="purpose">Purpose</label>
<input type="text" name="purpose" id="purpose"  />                              

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

When I submit the form, I want to identify and add a class called 'error' for only the labels of inputs which having empty values using jQuery.

Please help me short this problem.

Thanks and regards, Rushenn.

回答1:

.homework {
   color: red;
}

$('#contact_form').submit(function(){ // listen to the submit event
    var err = 0;  // define a varible with initial value of 0
    $('input[type=text]', this).each(function(){ // iterate through the text inputs
       var val = $.trim(this.value); // trim and store the value
       // if the value is empty add a class to the previous label otherwise remove it(is it has)
       $(this).prev().toggleClass('homework', !val ); 
       if (!val) err++; // if the value is empty add 1 to the err variable  
    })
    return !err; // return false if there is one or more empty field(s)
})


回答2:

Try this:

$('#contact_form').submit(function() {
    $(this).find("input:text").each(function() {
        if ($.trim($(this).val()) == '') {
            $(this).css({ border: "2px red solid" });
            return false;
        }
    })
});


回答3:

$('form#contact_form').submit(function(){
    if($('#name').val() == ''){
        $('label[for="name"]').addClass('error');
        return false;
    } else if($('#email').val() == ''){
        $('label[for="email"]').addClass('error');
        return false;
    } else if($('#purpose').val() == ''){
        $('label[for="purpose"]').addClass('error');
        return false;
    }
    return true;
});