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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀