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?

7
  • what do you mean by keeping? after submitting you can get the value in php file right? Commented Mar 18, 2014 at 17:53
  • yeah it is passed to a php file using GET Commented Mar 18, 2014 at 17:55
  • What does the page url look like after you submit? Commented Mar 18, 2014 at 17:58
  • @LShetty scm.ulster.ac.uk/~b00518407/workspace/projectfile/… Commented Mar 18, 2014 at 17:59
  • @LShetty search.php?searchInput=&srch_author=&Year=1998&srch_publisher=&srch_category= Commented Mar 18, 2014 at 17:59

4 Answers 4

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]);
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.