Jump to content
Larry Ullman's Book Forums

Chapter 17, Script 17.1, Step 14, How To Set Up Sticky Value


Recommended Posts

Hi,

 

Anyone can help to code how to add the sticky value for the drop-down chosen language after a user hits the the 'submit' button so that the default value won't return to 'language' ($words ['language']) value, please?

 

Thanks in advance,

 

Eric

Link to comment
Share on other sites

When you're looping through the options and printing out the HTML for each one, check if the submitted value is equal to the option value, and if it is, add the selected="selected" attribute to the option.

That will make it sticky.

 

sorry, but can you share the code of it, please?

Link to comment
Share on other sites

I don't know exactly how your code is structured, but here's the basic idea:

 



$langs = array('English', 'French', 'Spanish', 'German', ...);
$selected_lang = (int) $_POST['lang']; // Typecast to int for validation purposes.


echo '<select id="lang" name="lang">';
foreach ($langs as $i => $lang) {
  echo '<option value="' . $i . '"';
  
  // This makes the selected value sticky.
  if ($lang === $selected_lang) {
    echo ' selected="selected"';
  }
  
  echo '>' . $lang . '</option>';
}
echo '</select>';

  • Upvote 1
Link to comment
Share on other sites

Hi HarleySan,

 

This is my form:

<?php
      echo '<form action="" method="get">
        <select name="lid" id="sel_lang">
          <option value="0">' . $langs['lang'] . '</option>';
          
 // Retrieve all the languages...
$q = "SELECT lang_id, lang_others FROM languages ORDER BY lang_eng ASC";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) > 0) {
  while ($menu_row = mysqli_fetch_array($r, MYSQLI_NUM)) {
    echo "<option value=\"$menu_row[0]\">$menu_row[1]</option>\n";
  }
}
mysqli_free_result($r);

        echo '</select>
        <input name="submit" type="submit" value="'. $langs['go']. '" />
      </form>';
mysqli_close($dbc);    //Close the database connection.
?>

Can you help, pls?

Link to comment
Share on other sites

 Share

×
×
  • Create New...