views:

78

answers:

3

Hey,

I'm putting together a fairly simple HTML/Javascript/PHP form (I am fairly new to all of these). One field of the form requires users to select an option from a reasonably long list (using a drop down list). The contents of the list are extremely unlikely to ever change. Is there a "better" way to populate the list than simply using a lot of <option> tags:

<select name="longlist">
    <option value="one">One</option>
    <option value="two">Two</option>
    ....
    <option value="sixty">Sixty</option>
</select>
+5  A: 

The resulting HTML will always have to have the option tags, but you may be able to generate it on the fly using PHP or jQuery.

For example

PHP

<select>
<?php
$myArray=array("One","Two","Three", "Four", "Five");
while (list($key, $val) = each($myArray))
  {
  echo "<option>" . $val . "</option>"
  }
?> 
</select>

jQuery

<select id="array-test"></select>

var myArray= ["One","Two","Three","Four","Five"];

$.each(myArray, function(index, value) { 
  $("#array-test").append("<option>" + value + "</option");
});
Marko
A: 

If you don't need to have the number in word form, e.g. 1 vs. 'one', you can save yourself the trouble of having to create the large array of words for the loop.

<select>
<?php
    for ($i = 1; $i <= 60; $i++){
        echo "<option>" . $i . "</option>";
    }
?>
</select>
cnanney
A: 

From a usability point of view, if the number of options is really that long, it's difficult to find the option you actually want.

Try to find a way to split the options up into categories and perhaps show two dropdowns: the first to choose the category, and the second to show only the options within the category. You can use jQuery to dynamically create the <option>s for the second dropdown based on the choice made in the first.

E.g

options = {
   "one": [1, 2, 3, 4],
   "two": [11, 12, 13, 14],
   "three": [21, 22, 23, 24]
}

$("select.select1").change(function() {
   var category = $(this).val() || $(this).text();
   if (options[category]) {
      $("select.select2").empty();
      for (var i in options[category]) {
         var newOption = $("<option>").text(options[category][i]);
         $("select.select2").append(newOption);
      }
   } else {
      $("select.select2").html("<option>Select a category first</option>");
   }
});

$("select.select1").change();

With HTML:

<select class="select1">
   <option>one</option>
   <option>two</option>
   <option>three</option>
</select>
<select class="select2">
   <!-- I am dynamically generated -->
</select>
box9
Knowledge Craving
@Knowledge Craving- I'm not sure I understand you but I'm not suggesting that the interface be changed to allow for dynamically generating the options, but that it should be changed for usability improvements. The code itself is the less important part, and helping the end user of the website narrow down to what he/she wants quicker is the more important.
box9
@box9 - I agree your last point.
Knowledge Craving