1

HTML

<td>
    <select name="Year" id="Year" value="">
        <option value=""></option>              
    </select> 
</td>

JavaScript to create the list

for (i = new Date().getFullYear(); i > 1900; i--)
{
    $('#Year').append($('<option />').val(i).html(i));
}

How do i keep the value of the year that is submitted?

nKn
  • 13,691
  • 9
  • 45
  • 62
Shay Young
  • 207
  • 3
  • 11

4 Answers4

2

In JS, since you have the year in the querystring, grab that and set it to the select box.

$('#Year').val(location.search.match(/year=([^&]+)/i)[1]);
lshettyl
  • 8,166
  • 4
  • 25
  • 31
1

The most obvious way is to pass $_POST['Year'] to a session or a cookie or to insert it into a database table and through PDO or MySQLi commands fetch the specific result anytime you want.

kidA
  • 1,379
  • 1
  • 9
  • 19
0

In your PHP you'll have access to the values that are posted. In this case it will be in $_POST['Year'], $_GET['Year'] or $_REQUEST['Year'], as Year is the name of your select.

The issue you have is that the select is built by javascript, rather than PHP. Because of that you need to set it using javascript too. Therefore you need to get the data from PHP into javascript - does that make sense to you?

OK.

So what you need to do, is generate a call to a javascript function using PHP. When the browser receives and renders the page it will run the javascript and set the value.

An example might be:

$year = $_POST['Year'];
echo( "<script>$('#Year').val('$year')<\script>" );

This would depend on how your PHP outputs the pages (I.E. what frameworks you are using, etc)

However, by far the simplest solution would be be actually build the select in PHP instead - if that's an option.

Rob Baillie
  • 3,436
  • 2
  • 20
  • 34
0

If the form is submitted to itself via GET, you can read the value from the querystring and set the value on the list:

for (var i = new Date().getFullYear(); i > 1900; i--)
{
    $('#Year').append($('<option />').val(i).html(i));
}
if (/[&?]Year=(\d{4})(&|$)/.test(location.search)) {
    var year = RegExp.$1;
    $('#Year').val(year);
}
Community
  • 1
  • 1
gilly3
  • 87,962
  • 25
  • 144
  • 176