Set variable on jQuery selector

Asked

Viewed 399 times

3

I saw some posts on the subject, but it did not help.

the problem is this:

CSS:

.spanClass{
 display: none;
}

HTML:

<input type="text" name="nome" id="nome">
<span class="spanClass"></span>

jQuery:

        $("#nome").on("keypress", function(){
            mask($(this), maskName);
        });

        function mask(o,f){
            v_obj = o;
            v_fun = f;
            setTimeout("execMask()",1)
        }

    function execMask(){
        var id = v_obj.attr('id'); // aqui eu pego o id 
        console.log(typeof(id)); // result: string
        v_obj.val(v_fun(v_obj.val(),id)); // aqui eu passo o valor do campo do meu input e o id dele.
    }


//nesta função eu recebo o regex, alvo(valor do input), uma msg, e o id(Sim já verifiquei no console, todos esses valores chegam até minha função alertMsg.

function alertMsg(regex,alvo,msg,id){
    if(regex.test(alvo)){
        $("#"+id).text(msg).fadeIn(); // esse comando não funciona.
    } else {
        $('#'+id).text("").fadeOut(); // esse comando não funciona.
    }
}

Can anyone tell me why I can’t put a variable in the jQuery selector?

NOTE: the last command does not show any error in the console, it simply does not run, if I manually put the id it works.

OBJECTIVE: When placing NOT allowed characters, displays an msg below the input.

1 answer

2

SOLUTION:

CSS:

.spanClass{
 display: none;
}

HTML:

<input type="text" name="nome" id="nome">
<span id="nomeSpan" class="spanClass"></span>

jQuery:

function mask(o,f){
    v_obj = o;
    v_fun = f;
    setTimeout("execMask()",1)
}

function execMask(){
    var id = v_obj.attr('id');
    v_obj.val(v_fun(v_obj.val(),id));
}

function replaceName(){
    $("#nome").on("keypress", function(){
        mask($(this), maskName);
    });
}

function alertMsg(regex,alvo,msg,id){
    if(regex.test(alvo)){
        $("#"+id+"Span").text(msg).fadeIn();
    } else {
        $('#'+id+"Span").text("").fadeOut();
    }
}

TOPIC ERROR ABOVE:

I was taking the id of the input itself and wanting to display a message in SPAN with it, I just changed this line on html, <span id="nomeSpan" class="spanClass"></span>, and this line on jQuery $("#"+id+"Span").text(msg).fadeIn();, so I can display the message below the input that had the false if condition returned.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.