Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

320
Visualizações
is it possible to pass a value using javascript onclick listerner for various items in a loop?

I am having a challenge below with javascipt in combination with php including html forms.

On clicking the link, it submits only one value from the loop. i.e the first value from the while loop.

a screenshot of the result is provided here link to the image.

from the above , when i click on any other link it just retrns the first one.

what i need is that the link to post values based on each link clicked. my code is here.

if ($result = $conn->query($query)) {
    while ($row = $result->fetch_assoc()) {

        $client_name = $row["client_name"]; 

                echo "<form id='form_submit' action='index.php' method='post'>
                        <input type='hidden' name='name'  value='$client_name'/>
                        <a href='#' onclick='submitForm(name)'>$client_name</a>
                    </form>
                 <script>

                    function submitForm(name) {
                    let form = document.getElementById('form_submit')
                    form.submit()
                        }
                </script><br>"; 
                
    }
    $result->free();
} else
echo "no records found";

the form is designed to submitt to the same page where it is captured by other php file which checks if a value is posted and proceed with some execution from there,

the receiving php file queries data from the databse based on the values submitted by the link clicked,

which in this case the link clicked only submits the value for the first item.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You could do that in a cleaner manner with a single form rather than a potentially large number. There is no need to use ID attributes for every element which is what was causing the original issue - rely upon the event target to indicate which element/link was clicked or, as here, use this from within the callback.

<form name='clients' method='post' action='index.php'>
    <input type='hidden' name='name' />

<?php

    if( $result = $conn->query($query) ) {
        while( $row = $result->fetch_assoc() ) {
            printf( '<a href="#">%s</a>', $row["client_name"] );
        }
        $result->free();
        
    } else {
        echo "no records found";
    }
?>
</form>
<script>

    const oForm=document.forms.clients;
    const oInput=oForm.name;
    
    oForm.querySelectorAll('a').forEach(a=>{
        a.addEventListener('click',function(e){
            oInput.value=this.textContent;
            oForm.submit();
        })
    })
</script>





    
    
    

For the sake of completeness in light of the comment regarding a single event listener as opposed to one bound to each hyperlink. With this event bubbling is what makes it work. A common ancestor has the event listener bound to it ( the form ) and the event.target is inspected to find which element actually triggered the event. This does avoid multiple duplicate event listeners.

const oForm=document.forms.clients;
const oInput=oForm.name;

oForm.addEventListener('click',(e)=>{
    if( e.target!=e.currentTarget && e.target instanceof HTMLAnchorElement ){
        oInput.value=e.target.textContent;
        oForm.submit();     
    }
})

Further reading about Events & Event delegation

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda