Alek Angelov
Alek Angelov

Reputation: 111

Pre selected options on form depending on the link you're coming from?

So, I have a day, month and year select options in the form. The page is called new.php and the page that's linking to it is event.php?d=1&m=1&y=2015.

Because it's coming from that link I want the selection options to be on the corresponding date (1st of January, 2015).

Any help would be greatly appreciated

Upvotes: 0

Views: 66

Answers (3)

Martin Sansone - MiOEE
Martin Sansone - MiOEE

Reputation: 4399

If you are ok with using client side scripting (I recommend jQuery) then you could get the select boxes showing the correct data.

Set three JavaScript variables based on the URL string variables. Then on document ready use JavaScript/jQuery to set the select boxes to the JavaScript variables..

<?php
  $day = $_GET['d'];
  $month = $_GET['m'];
  $year = $_GET['y'];

  echo "<script type='text/javascript'>";
  echo "$(function() {";
  echo "$('#day').val(".$day.");"
  echo "$('#month').val(".$month.");"
  echo "$('#year').val(".$year.");"
  echo "});"
  echo "</script>"              
?>

Then have the select statements with an ID so that jQuery can update the correct elements within the DOM..

 <select id="day">
  <option value='1'>1</option>
  <option value='2'>2</option>
  <option value='3'>3</option>
 </select>

etc.. for the rest of the days, then the correct id for the month selector and also year selector.

Upvotes: 0

Titi
Titi

Reputation: 1153

One way is to look at the $_SERVER['HTTP_REFERRER'] variable and use parse_url() function to parse the url nicely and get the query variables from there, and then use them as your value in the form element. But like Cox mentions in the comment it's a bit unreliable as it is set by the client.

Another way would be to set either one or 3 session variable on the event.php page like so:

$_SESSION['d'] = $_GET['d'];
$_SESSION['m'] = $_GET['m'];
$_SESSION['y'] = $_GET['y'];

Then in your new.php file you start use the session variables as the value in the form element. Don't forget to start the session on both pages with session_start().

Upvotes: 0

Anonimous
Anonimous

Reputation: 11

<?php
    $day = $_GET['d'];
    $month = $_GET['m'];
    $year = $_GET['y'];

    $date = date('Y-m-d', strtotime($day . $month . $year));
?>

<input type="date" value="<?php echo $date; ?>">

Upvotes: 1

Related Questions