PHP Magento Tips

Show/Hide Admin Form fields using Javascript in Magento

Rate this posting:

Case: In Magento Admin form, you have two fields. One is a select field and let the other field be a text field. Now, you want to show/hide the text field based upon the option selected in the select field

Solution: There are two ways to achieve this. You can either use setAfterElementHtml or addFieldMap function.

1) Using setAfterElementHtml function

Suppose, you want to show/hide the following field:

                'label' => Mage::helper('vijay_festivalbackgroundimage')->__('Custom CSS selector'),
                'name'  => 'background_custom_target',
                'required'  => false,
                'note'=>'Input CSS selector, like .class or #id',

Here is the dropdown/select field. It’s a yes/no field. Suppose, upon selecting ‘Custom’, you will need to show the above mentioned field. And, upon selecting any other options, you will need to hide the above field.

Note the onChange parameter here. It’s calling onchangeStyleShow() JS function.

$typefield = $fieldset->addField(
                'label' => Mage::helper('vijay_festivalbackgroundimage')->__('Background Target'),
                'name'  => 'background_target',
                'required'  => true,
                'class' => 'required-entry',

                'values'=> Mage::getModel('vijay_festivalbackgroundimage/background_attribute_source_backgroundtarget')->getAllOptions(true),
                'onchange' => 'onchangeStyleShow(this.value)',

Here’s the Javascript function to show/hide field.

The setAfterElementHtml is called which contains Javascript code to show/hide field.

Here i added required class. In the same way you can add show/hide logic.

$typefield->setAfterElementHtml("<script type=\"text/javascript\">
            function onchangeStyleShow(e){
                if (e == 'custom'){
                } else {

Note: If you want to show/hide any element with a particular class name then you can use the following Javascript code.

function toggleField() {                                                
    $$(".your-class-name").each(function(ele) {
        if ($('select_field').getValue() == 0) {
        } else {

2) Using addFieldMap and addFieldDependence functions

Now, here is the field map and field dependence functions. The following code indicates that the field “background_custom_target” will be shown when ‘background_target’ is "custom" selected in select_field.

   ->addFieldMap('festivalbackground_background_target', 'festivalbackground_background_target')
         ->addFieldMap('festivalbackground_background_custom_target', 'festivalbackground_background_custom_target')
         ->addFieldDependence('festivalbackground_background_custom_target', 'festivalbackground_background_target', 'custom')
Tag : Magento
0 Comments On "Show/Hide Admin Form fields using Javascript in Magento"

Back To Top