Posts Tagged ‘select’

Php generate html select options from array

Tuesday, November 8th, 2011

Here’s a super obvious php snippet that generates a list of options for a “select” html form tag on the fly:


<select id="tf_select" name="tf_select"
onchange="update(this,document.getElementById('tf'));">
  <option value="">Select...</option>
  <?php
$a = array("New Haven","Rochester","New York","Washington D.C.","Seattle","Zurich");
foreach($a as $e)
{
  echo "<option value='".$e."'>".$e."</option>";
}
  ?>
  <option value="Other...">Other...</option>
</select>

Combined with the javascript from an earlier post, it should be very easy to generate selectors for php based forms.

Javascript select text item from list or “Other…”

Tuesday, November 8th, 2011

Here’s a snippet of javascript that hooks up a “select” tag with a text field “input” tag. When the user changes the select automatically


function update(select,input)
{
  if(select.value == "Select...")
  {
    input.value = "";
    input.readOnly = false;
  }else if(select.value == "Other...")
  {
    input.value = "";
    input.focus();
    input.readOnly = false;
  }else
  {
    input.value = selector.value;
    input.readOnly = true;
  }
}

<select id="tf_select" name="tf_select"
onchange="update(this,document.getElementById('tf'));">
  <option value="">Select...</option>
  <option value="Male">Male</option>
  <option value="Female">Female</option>
  <option value="Other...">Other...</option>
</select>
<input name="tf" id="tf" type="text" readonly value="">

Try it here: