Home > front end >  is it possible to pass a value using javascript onclick listerner for various items in a loop?
is it possible to pass a value using javascript onclick listerner for various items in a loop?

Time:01-28

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.

CodePudding user response:

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>
  •  Tags:  
  • Related