Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

329
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda