AstureS AstureS - 1 year ago 189
Javascript Question

YII2 dependent fields

I have DropDownList:

  • Calendar

  • Last day

  • Text input

And I need:

  • if a user chooses "Calendar", the calendar widget appears

  • if "Text input", a text input appears

  • if "Last day" is chosen, nothing appears

I found many options on the web, but they use AJAX, and unfortunately, I can't make it to work in my case.

I think it can be solved with JavaScript.

Here's my PHP:

$js = 'function Go(){ alert("ok!");}';
$this->registerJs($js, yii\web\View::POS_READY);

<?php echo $form->field($model, 'condition')->dropDownList($conditionList,
'id' => 'condition',
'class' => 'dependent-input',
'onchange' => 'Go()',

Answer Source

You can use jQuery to accomplish the showing and hiding of your calendar and text input widgets.

Your compiled HTML might look something like this:

<select class="hide-and-show" name="show-and-hide">
  <option selected disabled>Choose one</option>
  <option value="calendar">Calendar</option>
  <option value="text-input">Text Input</option>
  <option value="last-day">Last Day</option>

<div class="calendar hideable">CALENDAR GOES HERE</div>
<div class="text-input hideable">TEXT INPUT GOES HERE</div>

Hiding the .hideable elements until they are selected is accomplished with simple CSS:

.hideable {
  display: none;

And a little JavaScript + jQuery can handle the toggling of the hiding and showing of the widgets, like this:

var closerClass = "last-day";

$(".hide-and-show").change(function() {
  var selectValue = $(this).val();

  if (selectValue === closerClass) {
  } else {
    var classname = "." + selectValue;

I've created a Codepen example to demonstrate.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download