Jump to content

Do I need Value in my <option>??


doubledee

Recommended Posts

Do I need to add value to this select statement?

 

		
<select id="expYear" name="expYear">
<option></option>
<option>2011</option>
<option>2012</option>
<option>2013</option>
<option>2014</option>
<option>2015</option>
<option>2016</option>
<option>2017</option>
<option>2018</option>
<option>2019</option>
<option>2020</option>
</select>

 

 

 

Debbie

 

 

Link to comment
https://forums.phpfreaks.com/topic/232533-do-i-need-value-in-my/
Share on other sites

Why not build the field dynamically, as long as you're going to edit it anyhow. . .

 

$year = range( 2011, 2020 );
echo "<select id=\"expYear\" name=\"expYear\">\n
<option value=\"\"></option>\n";
foreach( $year as $v ) {
     echo "<option value=\"$v\">$v</option>\n";
}
echo '</select>';

Why not build the field dynamically, as long as you're going to edit it anyhow. . .

 

$year = range( 2011, 2020 );
echo "<select id=\"expYear\" name=\"expYear\">\n
<option value=\"\"></option>\n";
foreach( $year as $v ) {
     echo "<option value=\"$v\">$v</option>\n";
}
echo '</select>';

 

Since you suggested turning my static HTML into dynamic PHP...

 

How can I retain the option that the user chose when my form reloads?

 

(e.g. If the user chose "04" under "Month" and my form reloads, then "Month" is blank.)

 

 

Debbie

 

 

Just check for the value in the $_POST array and compare it to the value for the field. If they match, echo 'selected="selected"'.

$year = range( 2011, 2020 );
echo "<select id=\"expYear\" name=\"expYear\">\n
<option value=\"\"></option>\n";
foreach( $year as $v ) {
     $selected = (!empty($_POST['expYear']) && $_POST['expYear'] == $v ) ?  'selected="selected"' : '';
     echo "<option value=\"$v\" $selected>$v</option>\n";
}
echo '</select>';

Just check for the value in the $_POST array and compare it to the value for the field. If they match, echo 'selected="selected"'.

$year = range( 2011, 2020 );
echo "<select id=\"expYear\" name=\"expYear\">\n
<option value=\"\"></option>\n";
foreach( $year as $v ) {
     $selected = (!empty($_POST['expYear']) && $_POST['expYear'] == $v ) ?  'selected="selected"' : '';
     echo "<option value=\"$v\" $selected>$v</option>\n";
}
echo '</select>';

 

 

Awesome!!

 

Just what I needed, and without using JavaScript or Cookies or Sessions! :thumb-up:

 

Thanks,

 

 

 

Debbie

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.