Jquery - How to pass a variable to a jquery selector?

2

Hello, I'm new here (as well as very new in knowledge of js and jquery). I'm trying to pass the result of a variable to a jquery selector. More specifically I'm trying to pass (through the click event) the name of an id (among several existing, as they are dynamically created) to a variable. And after I've captured this id, I can use it as a selector (to refer to classes or id's of the same name). I pass the code I wanted to do:

        $( function() {
            $('#geral :input').click(function(){
            var VARIAVEL = $(this).attr('id');

            if ($(this).prop('checked')) {
            $('???VARIÁVEL???" :input').prop('checked','checked');
            } else {
               $('???VARIÁVEL??? :input').removeAttr('checked');
            }
        });

Reinforcing ... this variable would now be used to select "id's" and sometimes "class's" ... So I imagine using "." and the "#" in conjunction with it ... Perhaps the problem is very basic, but knowing this will help me through long (very long) hours of fruitless research on the internet.

On request I will paste some of the form code here, which is not complete and requires add-ons (but still wanting to know about the initial doubt):

    echo "<div id='geral'>";
    echo    "<form action='addmembro.php' method='post'>";
    echo      "<b><label for='estadoID'>Relação: </label></b><br>";
                foreach($estado_obtido as $indiceestado => $valorestado):
                $estado=mb_strtoupper($valorestado["estado_estado"], "UTF-8");
                $estado1=$valorestado["estado_estado"];
                $uf=$valorestado["estado_uf"];
                echo  "<div  class='estados'>"
                    . "<input id='{$uf}' type='checkbox' name='{}' value='{}'>"
                    . "<b><label>{$estado} </label></b><br>";                       
                    foreach($regiao_obtida as $indiceregiao => $valorregiao):
                    $regiao1=$valorregiao["mesorregiao_mesorregiao"];
                    $codregiao=$valorregiao["mesorregiao_cod2"];
                    $estado2=$valorregiao["mesorregiao_estado"];
                            if($estado2==$estado1):
                                echo  "<div class='regioes'>"
                                    . "<input  id='{$codregiao}' type='checkbox' name='{}' value='{}'>"
                                    . "<b><label'>{$regiao1} - {$estado}</label></b><br>";                                
                                foreach ($cidade_obtida as $indicecidade => $valorcidade):
                                $municipio=$valorcidade["regiao_municipio"];
                                $codmunicipio=$valorcidade["regiao_codmunicipio"];
                                $regiao2=$valorcidade["regiao_regiao"];    
                                    if($regiao2==$regiao1):
                                        echo  "<div  class='{$codregiao}'>"
                                            . "<input id='{$codmunicipio}' type='checkbox' name='' value=''>"
                                            . "<label>{$municipio} - {$estado2}</label>"
                                            . "</div>"; 

Thank you !!

    
asked by anonymous 09.10.2016 / 00:26

2 answers

4

Considering your solution, you can still simplify the code well:

$( function() {
    $('#geral :input').click(function(){

        // 1. não usar caixa alta em nomes de var
        // 2. não precisa de jQuery para pegar o id, use this.id
        var seletor = '.' + this.id + ' :input';

        // Como o Sergio tinha sugerido
        var estado = $(this).prop('checked');
        $(seletor).prop('checked', estado);

    } // faltava fechar o listener de click
});
    
10.10.2016 / 04:16
1

I was able to find the solution! Thank you to anyone who cared! To pass a variable to the jquery selector just use simple concatenation. In case the selector needs to reference a class can be done like this:

    $( function() {
        $('#geral :input').click(function(){
        var VARIAVEL = $(this).attr('id');

        if ($(this).prop('checked')) {
            $('.' + VARIAVEL + ' :input').prop('checked','checked');//(SOLUÇÃO AQUI!)
        } else {
            $('.' + VARIAVEL + ' :input').removeAttr('checked');//(E AQUI!)
        }
    });

(And to refer to an id, just change the '.', to '#', obviously.)

Special attention goes to the spacings (reason of my error in many attempts). The 'input' had to come with the space before the 'colon' (:), otherwise the code is read like this: ".VARIAVEL: input" (as a single statement - which does not exist).

;)

    
09.10.2016 / 19:58