Magento: Show/Hide Admin Form fields using Javascript

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:

1

2

3

$fieldset->addField('field_to_hide',text,array(

'label'=>$this->__('Test'),

));

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

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

1

2

3

4

5

6

7

$selectField->setAfterElementHtml('

<script>

functionshowHideField(){

$("field_to_hide").toggle()

}

</script>

');

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

1

2

3

4

5

6

7

8

9

10

11

functiontoggleField(){

$$(".your-class-name").each(function(ele){

if($('select_field').getValue()==0){

ele.setStyle({display:''});

$('any_other_field').setValue('hello');

}else{

ele.setStyle({display:'none'});

$('any_other_field').setValue(0);

}

});

}

2) Using addFieldMap and addFieldDependence functions

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

1

2

3

$fieldset->addField('field_to_hide',text,array(

'label'=>$this->__('Test'),

));

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

$selectField=$fieldset->addField('select_field','select',array(

'label'=>'Show/Hide Selection',

'name'=>'select_field',

'values'=>array(

array(

'value'=>1,

'label'=>'Show',

),

array(

'value'=>0,

'label'=>'Hide',

),

),

));

Now, here is the field map and field dependence functions. The following code indicates that the field “field_to_hide” will be shown when ‘1’ (i.e. ‘Show’ option) is selected in select_field.

1

2

3

4

5

6

$this->setChild('form_after',$this->getLayout()

->createBlock('adminhtml/widget_form_element_dependence')

->addFieldMap('select_field','select_field')

->addFieldMap('field_to_hide','field_to_hide')

->addFieldDependence('field_to_hide','select_field',1)// field_to_hide field will be shown when '1' (i.e. 'Show' option) is selected in select_field

About

Mukesh Chapagain is a graduate of Kathmandu University (Dhulikhel, Nepal) from where he holds a Masters degree in Computer Engineering. Mukesh is a passionate web developer who has keen interest in open source technologies, programming & blogging. more...