如何在Yii2上添加jQuery

如何在Yii2上添加jQuery

问题描述:

I'm trying to use some jQuery on my website. I tried to use the code from This Question

and i can't find my error. I tried to put he code on layot/main.php and on site/index.php and no result. Here is my simple jQuery Code:

 <select name="dropdown" size=1>
<option value="1">option 1</option>
<option value="2">option 2</option>
</select>

<?php
use yii\web\View;
$this->registerJs(' $("select[name="dropdown"]").change(function(){

if ($(this).val() == "2")
    alert("call the do something function on option 2");

});', View::POS_READY);
?>        

Please Help!!

--- EDIT --- It work on this way:

<?php
use yii\web\View;
$this->registerJs("
$('select[name="."dropdown"."]').change(function(){
$("."'#teste'".").html('call the do something function on option '+$(this).val());
if ($(this).val() == '2')
    alert('call the do something function on option 2');

 });", View::POS_READY);
 ?>   

There is mistake with quotes in your JS :

"select[name="dropdown"]"

Change it to

$this->registerJs(' $(\'select[name="dropdown"]\').change(function(){

if ($(this).val() == "2")
    alert("call the do something function on option 2");

});', View::POS_READY);