Reputation: 1149
I have the following that gives me a "Jump" menu to put a query in the current URL like ?date=2016-07
<?php
$date = explode('-', $_GET['date']);
$year = $date[0];
$month = $date[1];
?>
<form>
<select name="date" onchange="this.form.submit()">
<?php
for ($i = 0; $i <= 18; ++$i) {
$time = strtotime(sprintf('+%d months', $i));
$value = date('Y-m', $time);
$label = date('F Y', $time);
printf('<option value="%s">%s</option>', $value, $label);
}
?>
</select>
</form>
Once the page has jumped, I want to display the new date as the default value. I thought you did this by giving a "value" attribute to the select list, but that didnt work. Reading up on this further, you need to add "selected" to one of the options.
How would I add "selected" to one of the options if it matches the date query in the URL?
Upvotes: 0
Views: 538
Reputation: 168
<?php
$date = explode('-', $_GET['date']);
$year = $date[0];
$month = $date[1];
?>
<form>
<select name="date" onchange="this.form.submit()">
<?php
for ($i = 0; $i <= 18; ++$i) {
$time = strtotime(sprintf('+%d months', $i));
$value = date('Y-m', $time);
$label = date('F Y', $time);
if(strcmp($value,$_GET['date']) == 0)
//If 0, $value and $_GET['date'] are the same: The option is selected
printf('<option value="%s" selected>%s</option>', $value, $label);
else
printf('<option value="%s">%s</option>', $value, $label);
}
?>
</select>
</form>
Upvotes: 1
Reputation: 61
$selected = ($value == $_GET['date']) ? 'selected' : '';
printf('<option value="%s" %s>%s</option>', $value, $selected, $label);
Upvotes: 1