user2285451
user2285451

Reputation: 107

Foreach row jQuery dialog

I am building a div that is part of the homepage of a website. This div display a list of projects. The projects are all saved in a MySQL database. What I am trying to do is create a button next to each row that says 'Delete'. After clicking on delete, the user should be prompted with a jQuery UI dialog box asking for confirmation. When the confirms to delete the project, the project id has to be sent to a delete page(let's call it delete.php).

What I got working so far

This is where I am stuck though. On the deletion page I echo the project id to see if it works. Somehow the delete.php page always echo's the id of the first project. Meaning that jquery always sends the first project's id.

How can I solve this mystery?

$currents    =   new Project();
$currents    =   $currents->getProjects($_SESSION["user"], "finished");
echo "<table>";
foreach($currents as $current){
 echo "<tr><td>" . $current["name"] . "</td>
 <td><form method='post' class='deleteproject' action='/requests/request.php'/>
 <input type='hidden' name='projectid' value='" . $current['id'] . "' />
 <input type='button' value='Delete' class='deleteproject'></form></td></tr>";

}
echo "</table>";

Here is the jQuery;

<script>
  $(function()
  {
      $( ".deleteproject" ).click(function() {
          $( "#dialogbox" ).attr('title', 'Are you sure you want to delete this project?').dialog({
              height: 100,
              width: 350,
              modal: true,
              buttons : {
                  "Confirm" : function() {
                      $('.deleteproject').submit();
                  },
                  "Cancel" : function() {
                      $(this).dialog("close");
                  }
              }
          });
          return false;
      });
  });
  </script>

Upvotes: 0

Views: 436

Answers (1)

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

When doing $('.deleteproject').submit();, you always send the first .deleteproject and not the one clicked. To solve that, you can save the this reference and submit your parent form.

$( ".deleteproject" ).click(function() {
  $this = $(this);
  $( "#dialogbox" ).attr('title', 'Are you sure you want to delete this project?').dialog({
      height: 100,
      width: 350,
      modal: true,
      buttons : {
          "Confirm" : function() {
              $this.closest('form').submit();
          },
          "Cancel" : function() {
              $(this).dialog("close");
          }
      }
  });

side note : Your form class name is also .deleteproject, so your function will fire even if you dont click on the button, but on the form. Also, (not sure about this) i think your script will fire twice because of the event bubbling. A click on the button deleteproject is also a click on the form deleteproject.

Upvotes: 1

Related Questions