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

Asked

Viewed 1,926 times

2

Hello, I’m new here (as well as very new in js and jquery knowledge). I’m trying to pass the result of a variable to a jquery selector. More specifically I want to pass (through the click event) the name of an id (among several existing ones, as they are created dynamically) to a variable. And after capturing this id, I can use it as a selector (to refer to classes or id’s of the same name). I pass the code of what 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 "class’s"... So I imagine the use of "." and "#" together with it... Perhaps the problem is very basic, but knowing this will help me from long (very long) hours of fruitless internet searches.

On request I will paste part of the form code here, which is not completed and needs complements (but still wondering 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!!

  • 1

    What is this element $('???VARIÁVEL???" :input')? is not the same as the $(this)? That is, it would suffice $(this).prop('checked', $(this).prop('checked'));

  • Do you have one input inside another?! Or by chance several elements with the same ID? None of this is allowed.

  • Hello, Sergio..! Actually you can’t use this (I think). There are 140 options, with 6000 sub options. Each check group and subgroup was dynamically created by receiving specific names. All "embraced" by a div with "general" name id. I can capture the name of each id by the "click" event, but to get to these id’s that are inside the "general" div, I would need to take the name of their respective id’s to the selector... this selector will "trigger" the "sub-ids" and "sub-classes"... that’s why I don’t think I can do it with "this"... but I want to say what the respective id/class is. Obg!

  • Hi Favareto. No... But I have inputs within "div’s" and "sub div’s"... in pure html the inputs are below each other... but in reality there are "main" and "subsidiary" so to speak... Thanks for the interest!

  • Then if someone can instruct me on how to edit the post title, it would be nice... The ending is not "selector selector" but "jquery selector".. I got in the way of writing..! Thank you!!

  • Can you [Edit] the question and include the structure of your HTML? It can be a snippet, a group of these Divs and subdivs. Because I still think you can handle it without having to assemble a selector. But just to clarify your question, you can concatenate strings and variables with the operator +, thus: var algo = variavel + 'string' + outraVar + 'outra string';

  • If possible, also try to explain better what you are trying to do. You want to mark/deselect a checkbox, and others that depend on it automatically track?

  • Thanks for your attention @bfavaretto!! Ok, about the concatenation, but I would like to know if a variable can be used as selector. And if so, what would be the syntax (assuming it is treated as id and class). But ok, I’ll paste part of the remaining code so you have an idea.

Show 3 more comments

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
});
  • Thanks @bfavaretto for the tip (The high box was just to draw attention to the point of text that I had an interest in solving). I thank Fábio, but I just needed to know the previous step. As I said, it was to get dynamic id’s. This is why I want to store them in variables. Hugs

1

I was able to find the solution! Thanks to those interested! To pass a variable to the jquery selector just use simple concatenation. In case the selector needs to reference a class it 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 spacing (reason for my mistake in many attempts). The input had to come with the space before the 'two points'(:), otherwise the code is read like this: ". VARIABLE:input" (as a single statement - which does not exist).

;)

Browser other questions tagged

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