Dropdown javascript onload

2019-09-11 08:02发布

问题:

I have a dropdown menu, that has a onchange function. Once the function is executed it changes another dropdown menu. I need to make it so it executes the script onload.

1st dropdown:

echo $form->field($model, 'company_id')->dropDownList($items_company, ['prompt' => 'Select Company', 'style' => 'width:400px;', 'onchange' => '
            $.post("index.php?r=project/lists&id=' . '"+$(this).val(), function( data ) {
            $( "select#project-client" ).html( data );
            console.log("On change");
            console.log(data);
            });

        ',])->label('Company');

2nd dropdown:

echo '<label class="control-label">Company Client</label>';
echo Select2::widget([
'model' => $model,
'attribute' => 'client',
'theme' => Select2::THEME_BOOTSTRAP,
'options' => [ 'label' => 'Client',
    'multiple' => true, 'style' => 'width:400px;', 'overwriteInitial' => true],
'pluginOptions' => [
    'disabled' => false,
],
]);

This is what I tried:

$(document).ready(function () {
    var currentProjectCompany = $('#project-company_id').val();
    $.post("index.php?r=project/lists&id=' . '" + currentProjectCompany, function (data) {
        $("select#project-client").html(data);
        console.log("Company ID:");
        console.log(currentProjectCompany);
        console.log("Clients");
        console.log(data);
    });
});

回答1:

Move the onchange code into its own function (it should be there anyway), and execute that function in the ready() function.

That way it will fire both onchange and onload.



回答2:

I do the same check my code it may help you .But i use ajax and jquery.

For firs dropdown .

echo $form->dropDownListGroup(
                    $model 'id', array(
                'wrapperHtmlOptions' => array(),
                'widgetOptions' => array(
                    'data' => abc::getName($model->id),
                    'htmlOptions' => array(
                        'prompt' => 'Select Project',
                        'ajax' => array(
                                'type' => 'POST',
                                'url' =>  ( Yii::app()->createUrl('/' . $domain_name . '/qq/xyz/abc') ),
                                'update' => '#seconddropdownid',
                                //'dataType' => 'json',
                                'data'=>array('id'=>'js:this.value'),

                              )
                            ),
                        ),
              )
            );

in second dropdown :

 echo $form->dropDownListGroup(
                $project, 'tag', array(
            'wrapperHtmlOptions' => array(),
            'widgetOptions' => array(
                'data' =>$this->getProjectTags(),
                'htmlOptions' => array(
                    'prompt' => 'Select Tags',
                ),
            )
                )
        );

on change of the second list you can update the the list-view of yii .