这是我的代码https://jsfiddle.net/tusharj/0hoh109k/1/
这在jsfiddle中完美地工作,但是在yii2中使用此代码时,却无法正常工作
_form.php
<?= $form->field($model, 'relation')->checkboxList($relation, $options = ['class' => 'check']);} ?>
这是上面形式的html代码,上面的代码看起来像下面的inspect元素
<div id="employeedetails-relation" class="check">
<div class="checkbox"><label><input type="checkbox" name="Employeedetails[relation][]" value="1"> Father</label></div>
<div class="checkbox"><label><input type="checkbox" name="Employeedetails[relation][]" value="2"> Mother</label></div>
<div class="checkbox"><label><input type="checkbox" name="Employeedetails[relation][]" value="3"> Spouse</label></div>
<div class="checkbox"><label><input type="checkbox" name="Employeedetails[relation][]" value="4"> Child1</label></div>
<div class="checkbox"><label><input type="checkbox" name="Employeedetails[relation][]" value="5"> Child2</label></div>
<div class="checkbox"><label><input type="checkbox" name="Employeedetails[relation][]" value="6"> Father-in-law</label></div>
<div class="checkbox"><label><input type="checkbox" name="Employeedetails[relation][]" value="7"> Mother-in-law</label></div></div>
下面的代码在yii2中使用了jquery
<?php
$this->registerJs('
$(document).ready(function () {
$(\'#employeedetails-relation\').on(\'change\', \':checkbox\', function () {
var value = parseInt($(this).val());
var checkedEl = [];
$(\':checkbox:checked\').each(function () {
checkedEl.push(parseInt($(this).val()));
});
console.log(checkedEl);
$(\'#employeedetails-relation :checkbox\').prop(\'disabled\', false);
console.log(value);
console.log($.inArray(value, checkedEl));
if ($.inArray(1, checkedEl) > -1 || $.inArray(2, checkedEl) > -1) {
$(\':checkbox[value=6]\').prop(\'disabled\', true);
$(\':checkbox[value=7]\').prop(\'disabled\', true);
} else if ($.inArray(6, checkedEl) > -1 || $.inArray(7, checkedEl) > -1) {
$(\':checkbox[value=1]\').prop(\'disabled\', true);
$(\':checkbox[value=2]\').prop(\'disabled\', true);
}
});
});', \yii\web\View::POS_READY);
?>
我不知道为什么它不能在yii2中工作
最佳答案
试试这行得通
namespace frontend\modules\test\assets;
use yii\web\AssetBundle;
class YourAsset extends AssetBundle
{
/**
* @inheritdoc
*/
public $sourcePath = '@frontend/modules/test/assets';
/**
* @inheritdoc
*/
public $publishOptions = [
'forceCopy' => YII_DEBUG,
];
/**
* @inheritdoc
*/
public $js = [
'js/your-file.js',
];
/**
* @inheritdoc
*/
public $depends = [
'yii\web\JqueryAsset',
];
}
关于php - jQuery在Yii2中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30321074/