CJuiSelectable 封裝 jQuery UI Selectable,將清單項目變為可框選/點選的互動元素,支援單選/多選、鍵盤操作與選取事件回調。
<?php
Yii::app()->clientScript->registerCss('selectable', "
#selectable { list-style:none; margin:0; padding:0; width:60%; }
#selectable li { margin:2px; padding:4px; border:1px solid #ddd; background:#f7f7f7; cursor:default; }
#selectable .ui-selecting { border:1px solid #fad42e; background:#fff9e6; }
#selectable .ui-selected { border:1px solid #fad42e; background:#fcefa1; font-weight:bold; }
#select-result { margin:10px 0; padding:5px; background:#f0f0f0; }
", 'screen', CClientScript::POS_HEAD);
?>
<h2>可選取清單</h2>
<center id="select-result">未選取任何項目</center>
<?php $this->widget('zii.widgets.jui.CJuiSelectable', array(
'id' => 'selectable',
'items' => array(
'id1' => '項目一:台北市',
'id2' => '項目二:新北市',
'id3' => '項目三:桃園市',
'id4' => '項目四:台中市',
'id5' => '項目五:高雄市',
),
'options' => array(
'filter' => 'li', // 可選取的子元素
'tolerance' => 'touch', // 判定選取演算法
'selected' => 'js:function(event, ui) {
updateSelection();
}',
'unselected' => 'js:function(event, ui) {
updateSelection();
}',
'stop' => 'js:function(event, ui) {
updateSelection();
}',
),
)); ?>
<script>
function updateSelection() {
var selected = $("#selectable .ui-selected");
var texts = selected.map(function() { return $(this).text(); }).get();
$("#select-result").text(texts.length ? "已選取: " + texts.join(", ") : "未選取任何項目");
}
</script>
| 選項/事件 | 說明 |
|---|---|
filter | 可選取元素選擇器(預設 '*') |
tolerance | 'fit'(完全包含) / 'touch'(接觸即選取) |
selected | 單項被選取時觸發 |
unselected | 單項取消選取時觸發 |
start | 開始框選 |
stop | 結束框選(滑鼠釋放) |
<?php $form=$this->beginWidget('CActiveForm'); ?>
<?php echo $form->hiddenField($model, 'selected_ids'); ?>
<?php $this->widget('zii.widgets.jui.CJuiSelectable', array(
'id' => 'user-selectable',
'items' => CHtml::listData(User::model()->findAll(), 'id', 'username'),
'options' => array(
'stop' => 'js:function() {
var ids = $("#user-selectable .ui-selected").map(function() { return this.id; }).get();
$("#User_selected_ids").val(ids.join(","));
}',
),
)); ?>
<?php echo CHtml::submitButton('批次刪除'); ?>
<?php $this->endWidget(); ?>
id 屬性需為唯一識別碼