简体   繁体   中英

JQuery selecting only the element inside the selected one

I'm currently having problem selecting the right element on a form

Here is my code:

$(document).ready(function(){
    $(".wpcf7-submit").click(function () {
        if($('.errorName').length > 0){
            return false;
        }
    });

    var selectorArray = [$('input[name="name"]'), $('input[name="Company"]')];
    $.each(selectorArray, function(){
      $(this).on('blur',function(){
        if($('.errorName').length == 0 && (($(this).val().length < 4  && $(this).val().length != 0) || /^[a-zA-Z0-9- ]*$/.test($(this).val()) == false))
        {
            $(this).after('<span class="wpcf7-not-valid-tip errorName" role="alert">Field is not right.</span>');
        }
        else
        {           
            if($(this).val().length > 3 && /^[a-zA-Z0-9- ]*$/.test($(this).val()) == true) 
            { 
               $(this).find('.errorName').remove();
            }
        }
      });
    });
});

Basically, I want to check, on unfocus, if what the user has input is good for a couple of fields inside the form, else an error message appears. Unfortunately, I can't seem to remove the error message, and this code stucks that message on the first field the user inputs wrong. After that, it won't come off even if the input typed after the first unfocus satisfies the conditions.

I'm testing on a simple form with 2 text inputs and 1 submit. Without the remove part, I can see both messages being displayed and on

$(this).find('errorName').first().remove();

It's the second element that gets stuck with the error message.

You're placing the errorName span after the input element, so you need to look for a sibling instead. You can use .next() for this.

$(this).next('.errorName').remove();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM