user5469526 user5469526 - 1 year ago 137
MySQL Question

Dynamic Form with Dependent drop down

Hey Developers i'm building a application form where the user input data into the different fields. One part of the application is a dynamic form from Now inside the dynamic form i have a dependent drop down but when i click the [+] sign the dependent drop down change data on the first row and not the second.

Here's my code.

in my controller

public function actionLists($name)
$countHs= Hs::find()
->where(['hscode'=> $name])
$Hs = Hs::find()
->where(['hscode'=> $name])
if($countHs > 0)
foreach ($Hs as $H)
echo "<option value='".$H->hsproduct."'> ".$H->hsproduct."</option>";

echo "<option> - </option>";


and my form

<div class="col-sm-6" style="width: 135px">
<?= $form->field($modelsItems, "[{$i}]hscode")->dropDownList(




'$.get( "'.Url::toRoute('/hs/lists').'", { name: $(this).val() })
.done(function( data ) { $( "#'.Html::getInputId($modelsItems, "[{$i}]hsproduct").'" ).html( data ); } );'



<div class="col-sm-6" style="width: 135px">
<?= $form->field($modelsItems, "[{$i}]hsproduct")->dropDownList(

Im a newbie sorry for my english

Answer Source

Updated for your case.

What I did was I declared global variable in JS file var i and assigned 0. After the first event is fired, I increase variable i by one. Now it contains 1 in memory. Next time it will take 1 and add 1 again. And so on:

var i = 0;

$(document).on('change', 'select', function(e) {

Note that this will only work if you choose in each row just once and you will not come back to specific row. If you want to do something like that, you should instead get element ID's number, parse to float (instead of string) and use that number to your event script.


Leaving below one additional solution (but not according to yours). Just in case.

Use Inspect source and find how your input fields are named (name or ID). Let's say, we have name="hs-0-hscode". This is for just Then your jQuery:

$(document).on('change', 'select', function(e) {
    if ($(this)[0].id.indexOf('hscode') > 0) {
        // Now you can use Ajax to get a list of items you want to show.
        // Element itself can be reached: $(this).parent().parent().parent().children().eq(1);
        // For example:
        // var data = $.parseJSON(results);
        // $.each(data, function(key, value) {
        //    $('#client-company_size')
        //        .append($("<option></option>")
        //        .attr("value", key)
        //        .text(value)); 
        // });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download