Select values of a <td> with click

Asked

Viewed 488 times

2

The code below is for a page, which the user enters the name of a city, and checks if there are similar results. With this, it brings several results in a table created dynamically, depending on the data brought from the results, this is already working.

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

<?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>

  <script text="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>
  • I think that you have to pass the element itself clicked on the function. Example: <td id="td" onclick="mostraConteudo(this)"><?= $linha['cidade']?></td>

  • Why don’t you use Html5 data-attrs instead of taking the html value?

2 answers

3


The problem is that you are setting the attribute id an element that repeats on the page. The attribute id must be unique and represent only one element. For example, the HTML generated by your PHP would be 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>

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

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

That is, remove the attribute id 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 as you will probably have to do a database search with this value, maybe it’s best you get the id (database) of this record. This can be done:

<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);
}

Thus, with the id, it will be easier to search the other data in the database.

  • Excellent Anderson! Had tried in a similar way, passing this as parameter, but was not doing right within the JS. Thanks for the help, it worked perfectly! Thank you!

1

Well, there are some things you need to fix in your code. I suggest you visit afterwards http://api.jquery.com/ to have a better understanding.

Come on:

Use class for elements that will repeat the ID of an element must be unique, in case I switched from id="td" for class="tdCidade".

Now the part that interests you the most: In the code below every time you click on an element of the class tdCidade taken 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>
<table class="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>         

Browser other questions tagged

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