I am trying to get a select list to automatically hide/show other form fields based on a user input in the select box.

If the form is changed to the 1st item in the list then the div id="destdiv" should be shown. if not it should collapse and not be shown. I have been banging my head on this for a few days. I can get a checkbox to work, but not a select list.

Thanks in advance

 $form['dest_lid']  = array(
    '#type' => 'select',
    '#title' => t('Destination'),
    '#default_value' => $defaults['dest_lid'],
    '#options' => _freq_loc_array($defaults['uid']),
    '#description' => 'Please Choose an address. <br />If you have not added your current destination to the frequent Destinations to the address list please choose "Not a frequent Destination". If you need to edit an address in your list please click "Edit Address".',
    '#prefix' => '<table class="forms"><tr><td colspan="4">',
    '#attributes' => array('onclick' => 'destchange(this.selectedIndex)')
  );
<script...>
function destchange(value) {

  var mdiv=document.getelementbyid('destdiv');

  if(value == 1 ) {
    mdiv.style.display='';
  }
  else {
    mdiv.style.display='none';
  }
}
</script>

Comments

naveenpl’s picture

Hi robogeek,
onchange attribute works fine. Please check your code, you just made a mistake.

 $form['dest_lid']  = array(
    '#type' => 'select',
    '#title' => t('Destination'),
    '#default_value' => $defaults['dest_lid'],
    '#options' => _freq_loc_array($defaults['uid']),
    '#description' => 'Please Choose an address. <br />If you have not added your current destination to the frequent Destinations to the address list please choose "Not a frequent Destination". If you need to edit an address in your list please click "Edit Address".',
    '#prefix' => '<table class="forms"><tr><td colspan="4">',
   // Mistake was made in the code given below.
   /* '#attributes' => array('onclick' => 'destchange(this.selectedIndex)')*/
  // Correct code.
   '#attributes' => array('onchange' => 'destchange(this.selectedIndex)')
  );
function destchange(value) { alert("Hai robogeek"); }
robogeek’s picture

I never thought of the alert function to help me debug before...

It helped my onchange was working but i found out that the document.getelementbyid() function didn't it had to be getElementById() and I didn't know that. so the javascript just stopped executing at that point...

Got what I needed working, thanks for your time to respond.