How can I show data linked to a drop-down option?

A user wanted to be able to display a serial number associated with some of the options in a large select drop down element. The request was to display the number if there was one, otherwise to hide the field. While this is an uncommon request the code is posted here because it could be adapted to meet various similar needs.

The options for the select drop-down were created using a Custom Code element with the serial number in a data-serial attribute like this

<select name='product_list' id='product_list' . . . >
<option id="hide_none3" value="BRILLIANT SPA® - #0361" data-serial='12345' > . . . </option>
. . .
</select>

Using a data- . . . attribute allows us to add data like the serial number to the form and stay compliant with HTML specifications so that the form will still validate if needed.

In this case the attributes were added by hand, but they could easily have been generated using PHP and data from a database table.
The serial number was to be displayed in a standard ChronoForms text input with the name and id set to serial_no. This could be replaced with a plain <span> or <div> if it didn't need to be editable.
Then the following code was added to a Load JS action in the form On Load event.
window.addEvent('domready', function() {
  $('serial_no_container_div').hide();
  $('product_list').addEvent('change', function() {
    var opt;
    opt = this.getSelected().getProperty('data-serial').toString();
    if ( opt.length > 0 ) {
      $('serial_no').value = opt;
      $('serial_no_container_div').show();
    } else {
      $('serial_no').value = '';
      $('serial_no_container_div').hide();
    }
  });
});
Here 'serial_no_container_div' is the id of the container div wrapping the serial number text input; the code hides and shows the whole div.
You can see a demo of this form {rokbox text=|here|}http://greyhead.org/index.php?option=com_chronoforms&tmpl=component&chronoform=test_form_option_attr{/rokbox}. Note that it only includes a small amount of test data.

ChronoForms v5 code

This is the equivalent JavaScript re-written using jQuery for use with ChronoForms v5 on Joomla! 3. 

jQuery(document).ready(function (jQ) {
  jQ('#form-row-serial_no').hide();
  jQ('#product_list').change(function () {
    var opt;
    opt = jQ(this).find(':selected').data('serial').toString();
    if (opt.length > 0) {
      jQ('#serial_no').val(opt);
      jQ('#form-row-serial_no').show();
    } else {
      jQ('#serial_no').val('');
      jQ('#form-row-serial_no').hide();
    }
  });
});
 
 
 

Comments:

You need to login to be able to post a comment.