Select values from a td with click

2

The code below is a page, which the user types the name of a city, and checks for similar results. With this, it brings multiple results into a dynamically created table, depending on the data brought back from the results, this is already working Ok.

I need to make sure that when I click on the table row corresponding to the desired result, the table is "cleaned" and the row data is stored so I can work with them, displaying other data related to the city selected in the table, but when I get the element by td it always brings me the first independent result of which I click. Any ideas I can work for?

<?php include_once 'conexao.php' 
?>
<html>
<head>
    <title>INDEX Foruns Regionais</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><scripttext="text/javascript">

    function mostraConteudo() {
      esconde();
      var nome = document.getElementById('td').innerHTML;
      alert(nome);
      }   

    function esconde() {
      $('.table td').hide();
      }

        $(document).ready(function(){
        $("p").click(function(){
            $(this).fadeOut();
        });
    });

  </script>

</head>
    <body>

    <h1>Pesquisa cidade</h1>

      <form onclick="" name="formulario_busca" method="post"/>
        <input type="text" name="nome_cidade"/>
        <input type="submit" name="busca"/>
      </form>

        <?php

        $busca = $_POST['nome_cidade'];

        $query = "SELECT * FROM cidades WHERE cidade LIKE '%".$busca."%'";
        $resultado = mysqli_query($conexao, $query);
        mysqli_fetch_array($resultado,$lista_Cidades);
        ?>

          <table class="table table-striped table-bordered"> 

              <?php
              if ((mysqli_num_rows($resultado)>0) && ($busca != "") ):
                while ($linha = mysqli_fetch_assoc($resultado)) { 

              ?>
          <tr>
            <td id="td" onclick="mostraConteudo()"><?= $linha['cidade']?></td>
          </tr>

              <?php

                } echo "<br/>";
                  endif;    if(mysqli_num_rows($resultado)<=0):
                    echo "Cidade não encontrada";
                    endif;
              ?>
        </table>
    </body>
</html>
    
asked by anonymous 06.09.2017 / 14:49

2 answers

3

The problem is that you are setting the id attribute on an element that repeats on the page. The id attribute must be unique and represent only one element . For example, the HTML generated by your PHP would look something like:

<tr>
  <td id="td" onclick="mostraConteudo()">Cidade A</td>
</tr>
<tr>
  <td id="td" onclick="mostraConteudo()">Cidade B</td>
</tr>
<tr>
  <td id="td" onclick="mostraConteudo()">Cidade C</td>
</tr>

Since id is unique, the browser will only recognize the first line as #td and the others will be ignored. To work around this, you can change to:

<tr>
  <td onclick="mostraConteudo(this)"><?= $linha['cidade']?></td>
</tr>

That is, remove the id attribute and pass this as a parameter of mostraConteudo . So, such a function can be something like:

function mostraConteudo(elemento) {
    esconde();
    var nome = elemento.innerHTML;
    alert(nome);
}

And since you probably have to search the database with this value, you might want to get the id (from the database) of this record. This can be done like this:

<tr>
  <td data-id="<?= $linha['cidade']?>" onclick="mostraConteudo(this)"><?= $linha['id']?></td>
</tr>

And in JavaScript:

function mostraConteudo(elemento) {
    esconde();
    var id = elemento.dataset.id;
    var nome = elemento.innerHTML;
    alert(id);
}

So, with id , it will be easier to fetch the other data in the database.

    
06.09.2017 / 14:58
1

Well there are some things you need to fix in your code. I suggest you visit link for a better understanding later.

Come on:

Use class for repeating elements The ID of an element should be unique, in the case I switched from id="td" to class="tdCidade" .

Now the part that interests you the most: In the code below every time you click an element of class tdCidade I get the contents of the element that was clicked using $ (this) .html ();

$(".tdCidade").on("click", function(){
    alert($(this).html());
    esconde();
});

$(document).ready(function(){
  $("p").click(function(){
      $(this).fadeOut();
  });
  
  $(".tdCidade").on("click", function(){
    alert($(this).html());
    esconde();
  });
});

function esconde() {
   $('.table td').hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><tableclass="table table-striped table-bordered">
  <tr>
    <td class="tdCidade">Santo André</td>
  </tr>
  <tr>
    <td class="tdCidade">São Bernardo</td>
  </tr>
  <tr>
    <td class="tdCidade">São Caetano</td>
  </tr>
</table>         
    
06.09.2017 / 15:05