select

Normally you would select an option with a server-side script like PHP which is a lot faster and doesn't require the client's browser to do the work. But on the rare occasion where you need to set an option with JavaScript, here's a small script on how to do it.

  1.  
  2. document.getElementById('select_box_id_here').value
  3. = 'the value of the one you want selected';
  4.  

This will work if you have constructed the page the proper way. On the odd chance you've used JavaScript to pull in a whole string of HTML then use the method below.

  1.  
  2. var selectBox = document.getElementById('select_box_id_here');
  3. for(i=0; i<selectBox.options.length; i++) {
  4. if(selectBox.options[i].value == a_value) {
  5. selectBox.options[i].selected = true;
  6. i = selectBox.options.length;
  7. }
  8. }
  9.  

The above script simply loops through your select box and determines if the current option (in the loop) matches the value (a_value), if so then set the option to selected. The line "i = selectBox.options.length;" simply stops the 'for loop' from checking any further options.

The reason why you have to manually go through the select box yourself is because the DOM doesn't actually know the select box is on the page when you've just dumped a whole lot of HTML into the page with JavaScript. If it's possible to refresh the DOM then let me know, otherwise the above option is the solution to this problem.

User Level: Beginner to Intermediate

  1.  
  2. < ?php
  3. class MySQLHandler {
  4. var $mysql_host;
  5. var $mysql_username;
  6. var $mysql_password;
  7. var $mysql_marking_database;
  8. var $link;
  9. var $select_db;
  10.  
  11. function MySQLHandler($database_name) {
  12. $this->mysql_host = "INSERT_HOST_HERE";
  13. $this->mysql_username = "INSERT_USERNAME_HERE";
  14. $this->mysql_password = "INSERT_PASSWORD_HERE";
  15. $this->mysql_marking_database = $database_name;
  16. }
  17.  
  18. function open_mysql_link() {
  19. $this->link = mysql_connect($this->mysql_host,
  20. $this->mysql_username, $this->mysql_password);
  21. $this->select_db = mysql_select_db(
  22. $this->mysql_marking_database, $this->link);
  23. return $this->link;
  24. }
  25.  
  26. function close_mysql_link() {
  27. mysql_close($this->link);
  28. }
  29. }
  30. ?>
  31.  

The above PHP script (mysql_handler.php) can be used to connect to your MySQL database with PHP.

  1.  
  2. < ?php
  3. include('classes/mysql_handler.php');
  4. $mysql = new MySQLHandler("database_name");
  5. ?>
  6.  

The include line will allow you to make references to the class, the 2nd line will allow you to initiate the class with a database name.

  1.  
  2. $mysql_link = $mysql->open_mysql_link();
  3.  

Then when you need a link for your MySQL functions, all you need to do is specify the above script and you're connected.

You may want to further secure this file by placing your host, username, and password details elsewhere.