doulipi3742 2016-11-29 08:27
浏览 74
已采纳

将javascript值传递给Yii2中的表单操作URL

I'm trying to put a value from javascript into a form action in Yii2 is it possible? More specifically I need to make a URL change for each option that is selected in a dropdownList.

form in views/site.php

$form = ActiveForm::begin([
       'id' => 'form',
       'method' => 'POST',
       'action' => Url::to(['programas/'.Tours::findOne(['pk' => ])->programa]),
]); 

<?= $form->field(new \app\models\Tours(), 'nombre')->dropDownList([],
    [
        'prompt' => 'Programa',
        'id' => 'child1_child2',
        'onchange' => 'updateValue(this.value)',
   ]
)->label(false); ?>

Js file

    function updateValue(val){
  x = document.getElementById("test").value;
  // document.getElementById("form").action = "programas/";
}

So, I rescue the value from the selected option with JS but I need to put it in here 'pk' => 'value'

where value is the #child1_child2 selected option value.

'action' => Url::to(['programas/'.Tours::findOne(['pk' =>  ])->programa])

Thanks for the help.

  • 写回答

1条回答 默认 最新

  • drt41563 2016-11-29 11:29
    关注

    You can use one of the following approach with some modification:

    //pk => programa
    $data = [
      1 => 'programa1',
      2 => 'programa2',
      3 => 'programa3',
    ];
    

    1) Use JS

    <?= $form->field(new \app\models\Tours(), 'nombre')->dropDownList($data, ['prompt' => 'Programa'])->label(false); ?>
    

    JS

    $this->registerJs('
    $("#dropdownID").change(function() {
        var text = $("#dropdownID option:selected").text();
        $("#formID").attr("action", "/pathtoproject/programas/" + text);
    });
    ', \yii\web\View::POS_END);
    

    2) Use Ajax Call

    <?= $form->field(new \app\models\Tours(), 'nombre')->dropDownList($data, [
       'prompt' => 'Programa',
        'onchange'=> '$.get( "'.Url::toRoute('get-action').'", { id: $(this).val() } )
           .done(function( data ) {
               $("#formID").attr("action", data); 
           } 
        );'
    ])->label(false); ?>
    

    Controller

    public function actionGetAction($id)
    {
       $name = Tours::findOne(['pk' =>  $id])->programa];
       echo \yii\helpers\Url::to(['programas/'.$name]);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法