Put variable in the jQuery selector

0

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

The problem is as follows:

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 not put a variable in the jQuery selector?

PURPOSE: When you enter NOT allowed characters, display a msg below the input.

    
asked by anonymous 12.12.2017 / 19:05

1 answer

0

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

    
12.12.2017 / 20:12