Romain
Romain

Reputation: 105

Checking which button is pressed with two forms

I have two forms in my webpage, one with a field and a button and the other with two fields and a button.

I have a hard time checking which form's button is pressed, any advice is welcome on how to handle this.

<form class="form-inline" action="somewhere.php" method="post">
<div class="form-group">
  <label for="date">Date:</label>
  <input type="text" class="form-control" name="date" id="date" placeholder="abc">
</div>

<button type="submit" class="btn btn-default">Submit</button>
</form>


<form class="form-inline" action="somewhere.php" method="post">
<div class="form-group">
  <label for="date1">Date 1:</label>
  <input type="text" class="form-control" name="date1" id="date1" placeholder="abc>
</div>
<div class="form-group">
  <label for="date2">Date 2:</label>
  <input type="text" class="form-control" name="date2" id="date2" placeholder="abc">
</div>

<button type="submit" class="btn btn-default">Submit</button>
</form>

And what is supposed to check what button is pressed.

$date = $_POST['date'];
$date1 = $_POST['date1'];
$date2 = $_POST['date2'];

if (!empty(date)) {
//do something
}
if (!empty($date1) && !empty($date2)) { 
//do something else
}

Upvotes: 0

Views: 57

Answers (2)

Ahmed Ginani
Ahmed Ginani

Reputation: 6650

First give name attribute in button.

<button type="submit" name="button1" class="btn btn-default">Submit</button>

<button type="submit" name="button2" class="btn btn-default">Submit</button>

now php side check which button is pressed:

if(isset($_POST['button1']){
  //Do something.
 }
else if(isset($_POST['button2'])
{
 //Do something.
}

Upvotes: 1

PHP Dev
PHP Dev

Reputation: 503

HTML

<button type="submit" name="btn1" class="btn btn-default">Submit</button>
<button type="submit" name="btn2" class="btn btn-default">Submit</button>

PHP

if(isset($_POST['btn1']){
  //put code here.
 }else{
    //put code here.
 }

Upvotes: 1

Related Questions