Home > Mobile >  How come multiple classes not targeting in textarea?
How come multiple classes not targeting in textarea?

Time:10-07

I want to use validate_empty_field function for both classes .log and .log2. For some reason only .log is targeted but .log2 textarea is not. When you click on text area, if empty, both should show validation error if the other one is empty or if both empty.

$(document).ready(function() {

    $('#field-warning-message').hide();
    $('#dob-warning-message').hide();

    var empty_field_error = false;
    var dob_error = false;
//    $('input[type=text], textarea')
    $('.log, .log2').focusout(function () {
        validate_empty_field();
    });

    function validate_empty_field() {
        var field = $('.log, .log2, textarea').val();
//        var first_name_regex = /^[a-zA-Z ]{3,15}$/;
        if (field.length == '') {
            $('#field-warning-message').show();
            $('#field-warning-message').html("Please fill out form!");
            empty_field_error = true;
        } else if (field.length < 1) {
            $('#field-warning-message').show();
            $('#field-warning-message').html("Please fill out form!");
            empty_field_error = true;
        } else {
            $('#field-warning-message').hide();
        }
    }

    $('.verify-form').submit(function () {
        empty_field_error = false;
        dob_error = false;

        validate_empty_field();

        if ((empty_field_error == false) && (dob_error == false)) {
            return true;
        } else {
            return false;
        }
    })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<textarea ></textarea>
<textarea ></textarea>
<div id="field-warning-message"></div>

CodePudding user response:

You should pass the event to the handler so you have access to the target

Change your event listener line to this:

$('.log1, .log2').focusout(validate_empty_field);

and then accept an argument in validate_empty_field

function validate_empty_field(ev){
    var field = $(ev.target).val();
    if(!field.length){
        //textarea is empty!
    }else{
        //textarea is not empty!
    }
}

in fact, you could do all of this in an anonymous function you have already created, and use the on method to stick with JQuery best practices:

$('.log1, .log2').on('focusout', function(){
    if(!$(this).val().length){
        //this textarea is empty
    }else{
        //this textarea is not empty!
    }
});

And yes, adding one class to all textareas and swapping out .log1, .log2 for that class would be a better option.

EDIT: Final option should cover all requirements.

$('.log').on('focusout', function(){
    $('.log').each(function(){
        if(!$(this).val().length){
            //this textarea is empty
        }else{
            //this textarea is not empty!
        }
    }
});
  • Related