0

I need to display a list of elements and after each and every element a delete button is added dynamically. Whenever the user presses a delete button the corresponding element should be deleted and rest of the list should be shown. I have written the following php code to accomplish this:

for($i=0;$i<count($b);$i++)
 { 
   $a=$b[$i];
     echo "<li>$b[$i]</li> ";
   $p="remove"."$j";
   echo "<form  action='' method='post'> <input class='z' type='submit' name='$p'  value='delete'> </form>";
   $j++;

 }
  if($_POST['$p'])
{
   //code for deleting 
}

The problem is whenever the user presses the delete button only the last element added is getting deleted and rest of the buttons are not working.Please tell me how to detect which button has been pressed dynamically and delete the corresponding element using php.

Thank you

4
  • What does the resulting HTML look like? What does the code for determining which value to delete look like? Commented Jul 16, 2013 at 16:31
  • adding a <input type='hidden' name='toDelete' value='$j' /> might be a solution :? Commented Jul 16, 2013 at 16:32
  • if($_POST['$p'].. is your problem. That cannot be correct. Commented Jul 16, 2013 at 16:32
  • Hey What is $j ? you're using $i as looping element. then $j is for what ? Commented Jul 16, 2013 at 16:37

2 Answers 2

1

You need to associate each button with its respective element. You'll wanna do this dynamically with an id or hidden input or something.

for($i=0;$i<count($b);$i++)
 { 
   $a=$b[$i];
     echo "<li>" . $b[$i] . "</li> ";
   $p="remove" . $i;
   echo "<form  action='' method='post'>";
   echo "<input type='hidden' name='item' value='" . $i . "' />";
   echo "<input class='z' type='submit' name='delete'  value='delete'> </form>";
   $i++;

 }
  if($_POST['delete'])
{
   $item = $_POST['item'];
   //code for deleting $item
}
Sign up to request clarification or add additional context in comments.

Comments

0

You're putting each delete button in its own form - you could also add in a hidden input with the ID to remove?

 echo "<form  action='' method='post'>\n";
 echo "<input type='hidden' name='toDelete'  value='" .$i ."'>\n";
 echo "<input class='z' type='submit' name='$p'  value='delete'>\n";
 echo "</form>\n";

You'd then look for the element to delete with:

if(isset($_POST['toDelete'])) {
   // $_POST['toDelete'] has the index number of the element to remove
}

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.