2

Consider the following:

<? php foreach($queryResult as $res) : ?>
    // output all table columns
    <form onsubmit="return javascriptFunction(); " method="post">
    <button id="b">edit</button>
    </form>
<?php endforeach; ?>

Obviously, when the javascript function is called, the id of the buttons are the same, so:

document.getElementById(b).value;

won't work as expected. Is it possible to:

  • Give each button a unique id attribute while it is created in the loop?
  • Say I click the third button, is it possible for the javascript function to use that button that is clicked?

I absolutely have know idea how it can happen, looks like there's no way around it. Is this possible?

1

2 Answers 2

2

To give to each button a different id you can do this way:

<?php 
$i = 1; 
foreach($queryResult as $res) {  ?>
    // output all table columns
    <form onsubmit="return javascriptFunction(); " method="post">
    <button id="element-<?= $i ?>">edit</button>
    </form>
<?php $i++; } ?>

For the second question: if you want to pass the id of the button to javascriptFunction you can modify your code this way:

return javascriptFunction(<?= '\'element-'. $i . "'" ?>); 

and when javascriptFunction will be called, it will be passed the id of the button as the parameter and you could use it inside the function

Sign up to request clarification or add additional context in comments.

5 Comments

when I try onsubmit="return javascriptFunction(<?= 'element-'$i ?>); ", it gave me an error saying undefined $i, expected "," or ";"
I just changed it to onsubmit="return javascriptFunction(<?= 'element'+$i ?>); " it's working now.
yes, there was an error: my purpose was to pass the string 'element-n' to the function. I have updated the code, now it should work
ok, but why does this work? onsubmit="return javascriptFunction(<?= 'element'+$i ?>); "
probably because it's evalutated in javascript, but not sure what it will produce...you could check in the HTML code
0

You can use a forach and then you dont' have to keep track of the id iterator

foreach($queryResult as $id=>$res) {  ?>
    // output all table columns
    <form onsubmit="return javascriptFunction(); " method="post">
    <button id="element-<?php echo $id ?>">edit</button>
    </form>
<?php $i++; } ?>

Also, FWIW, its of course terrible practice to have multiple elements with the same id, but document.querySelectorAll('#someID'); will give you multiple elements in most browsers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.