How to display a person’s name within the title="" tag label that is in a <input> in a PHP form?

Asked

Viewed 84 times

-2

I’m making a system accessible to a visually impaired person and my biggest challenge is to make things accessible, on my Atualizar cliente the person chooses the customer on the ID cliente that returns a <select> with all registered customers, what I would like to know is the following:

  • How do I display a chosen person’s name on ID cliente to be displayed in the inputs below by the label tag known as title=""?

Example :

  • ID Cliente has two clients: Leandro and Maria
  • Nome has a legend tag called title="" that is written as title="Campo para atualizar o nome de".
  • This one: <p> Nome: <input type="text" name="nome" id="nome" title="Campo para atualizar o nome de" size=30 maxlength="30" required=""> </p>
  • Every time I chose Leandro on ID cliente the tag title="" in the input Nome would show title="Campo para atualizar o nome de Leandro" when I mouse this input.
  • Every time I picked Maria on ID cliente the tag title="" in the input Nome would show title="Campo para atualizar o nome de Maria" when I mouse this input.

The image

inserir a descrição da imagem aqui

The code

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <title> Atualizar cliente </title>
    <link rel="stylesheet" href="/WEB/css/css.css"> 
    <script>
        function exibirNome() {
            var nome = document.querySelector("#nome").value;
            if (nome) {
                alert(nome + " foi atualizado(a) com sucesso!");
            }
        }
    </script>
</head>
<body>
    <?php
        require_once '../conexao/conexao.php'; 
        if(isset($_POST['Atualizar'])){  
            $cd_cliente = $_POST['cd_cliente'];
            $nome = $_POST['nome'];
            try {
                $atualizacao = "UPDATE cliente SET nome = :nome WHERE cd_cliente = :cd_cliente";
                $atualiza_dados = $conexao->prepare($atualizacao);
                $atualiza_dados->bindValue(':cd_cliente',$cd_cliente);
                $atualiza_dados->bindValue(':nome',$nome);
                $atualiza_dados->execute(); 
            } catch (PDOException $falha_atualizacao) {
                echo "A atualização não foi feita".$falha_atualizacao->getMessage();
            }
        }
        // Query que seleciona chave e nome do cliente
        $seleciona_nomes = $conexao->query("SELECT cd_cliente, nome FROM cliente");
        // Resulta em uma matriz
        $resultado_selecao = $seleciona_nomes->fetchAll();  
    ?>
    <form method="POST">
        <p> ID cliente:
        <select name="cd_cliente" required="" title="Caixa de seleção para escolher o cliente a ser atualizado">
            <option value="" title="Opção vazia, escolha abaixo o cliente a ser atualizado"> </option>
            <?php
                foreach ($resultado_selecao as $valor) {
                    echo "<option value='{$valor['cd_cliente']}'>{$valor['nome']}</option>";
                }
            ?>
        </select>
        </p>
        <p> Nome: <input type="text" name="nome" id="nome" title="Campo para atualizar o nome de"  size=30 maxlength="30" required=""> </p>
        <p> <input type="submit" name="Atualizar" onclick="exibirNome()" title="Botão para confirmar a atualização do cliente" value="Atualizar cliente"> </p>
    </form>

3 answers

3

You can initially leave the input without the attribute title, and use the event change to concatenate the default title text + the name of the person selected in select:

document.addEventListener("DOMContentLoaded", function(){ // aguarda o carregamento do DOM
   
   const cd_cliente = document.querySelector('[name="cd_cliente"]'); // seleciona o select
   const title = 'Campo para atualizar o nome de '; // string padrão do title
   
   cd_cliente.addEventListener("change", function(){ // evento change
      let texto = this.options[this.selectedIndex].textContent.trim(); // pega o texto do option selecionado
      // se o value do select não for vazio, concatena o nome,
      // caso contrário o title fica vazio
      document.getElementById("nome").title = this.value ? title + texto : '';
   });
   
});
<p> ID cliente:
<select name="cd_cliente" required="" title="Caixa de seleção para escolher o cliente a ser atualizado">
   <option value="" title="Opção vazia, escolha abaixo o cliente a ser atualizado"> </option>
   <option value='1'>Leandro</option>
   <option value='2'>Maria</option>
</select>
</p>
<p> Nome: <input type="text" name="nome" id="nome" size=30 maxlength="30" required=""> </p>
<p> <input type="submit" name="Atualizar" onclick="exibirNome()" title="Botão para confirmar a atualização do cliente" value="Atualizar cliente"> </p>

  • Tio, Error { "message": "Referenceerror: displayNome is not defined", "filename": "https://stacksnippets.net/js", "lineno": 1, "colno": 1 }

  • Oops! Where is this?

  • It’s there in the Ubmit input. I think it’s better that you take it, because this Ubmit won’t even influence the answer. Or take the function being called on the onclick from that button.

  • on run, choose client ID by clicking Update client and gives this error

  • @Leocaracciolo But not pro Submit work in the same snippet not. It has to work only there in the author’s code of the question.

  • Right, so why run it? Put the codes without this option to run

  • @Leocaracciolo Run is to see the code working. When you select a name in select, the input title is changed, which is the heart of the matter.

  • here only gives error

  • the selected name does not go pro input

  • @Leocaracciolo Where does the question say the name should go pro input? D

  • So I didn’t understand the question, much less the answer. Cat’s does this

  • @Leocaracciolo I understood the question. In the title says "How to display a person’s name within the title="" tag label that is in a <input> in a PHP form? [closed]" and in the middle says "How do I display the name of a person chosen in the client ID to be displayed in the inputs below by the label tag known as title=""?".. Note that in both he makes it clear that he wants the name to be displayed in the attribute (he called it "tag") title, and not the input itself.

  • You’re the guy, ATTRIBUTE and no tag. Now it’s good

  • Leozão, the boy of the question just asked to put in the title of the same input. I put appearing in the input (also) just to give a plus of the answer and to show you how things happen. Rs

  • 1

    @sam is my master !

  • ................ ;D

  • Interesting code.

Show 12 more comments

3

See if that answer solves your problem:

We added an event onchange to your select(This event happens when we change the select (option) option)

The "this" means that you will take that element that undergoes the event (which in this case is the select) and pass it as parameter to the function.

Then, we take the value of select (the value your select currently has).

Finally, we assign the value that is in your select as the value of your input and also concatenate with the phrase that is displayed in your title.

//Criando função no JS (é chamado quando mudamos a opção do select)
function exibirNome(campo) {

  //Essa variável "campo" é o seu elemento <select>.

  //Verificando se o campo veio com valor vazio
  if (campo.value != "") {
    //Passando o valor (do select) para o title (concatenado com a frase) do <input>
    document.querySelector("#nome").title = "Campo para atualizar o nome de " + campo.value;

    //Passando o valor (do select) para o value do <input>
    document.querySelector("#nome").value = campo.value;
  } else {

    //Se o campo vier vazio, então entramos no else e passamos uma String vazia para o title e para o value do seu <input>
    document.querySelector("#nome").title = "";
    document.querySelector("#nome").value = "";
  }

}
<label for="opcao">ID Cliente: </label>
<!-- O "this" quer dizer que quando o evento onchange ocorrer, será passado o próprio elemento que sofre o evento (o <select>) para a função exibirNome() -->
<select id="opcao" onchange="exibirNome(this)">
  <option value="">Selecione</option>
  <option value="Leandro">Leandro</option>
  <option value="Maria">Maria</option>
</select>
<br><br>
<label for="nome">Nome: </label>
<input type="text" id="nome">

Any doubt is just talk, brothão.

  • Thanks helped me a lot this javascript.

  • You’re welcome, my brother. If that answer or any other answer helped you the most, click on the "V" of this question to accept such answer as being the solution to your problem

1

Add the following javascript function to your head

function onChangeSelect(select) 
{       
   document.getElementById("nome").title =  "Campo para atualizar o nome de " + select.selectedOptions[0].textContent;
}

And add function flame in the on change of select:

<select onchange="onChangeSelect(this)" name="cd_cliente" required="" title="Caixa de seleção para escolher o cliente a ser atualizado">

:)

  • Thanks helped me a lot this javascript.

Browser other questions tagged

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