通过select2动态选择分配给选项

时间:2013-09-08 13:45:53

标签: php jquery jquery-select2

我尝试在返回的get变量上通过php动态选择动态选择,但我无法弄清楚如何做到这一点。 我正在尝试以下但我想这需要用jquery来完成。 $grade是已审核的get varible

<select id="grade" name="grade" style="width:125px">
        <?php foreach ($abs as $index => $a): ?>

        <?php $grade == strtolower($index) ?  '<span class="select2-chosen">'.$a.'</span>': '' ?>
        <option value="<?php echo $index ?>"
                    ><?php echo $a ?></option>
        <?php endforeach; ?>
    </select>

2 个答案:

答案 0 :(得分:0)

<option value="<?php echo $index ?>" <?php if($index=="condition for adding selected"){echo "selected"} ?>
    <?php echo $a ?>
</option>

我不知道您何时想要添加“已选择”,但您可以像这样动态添加所选内容。

答案 1 :(得分:0)

前几天我遇到了问题,select2有一个名为initSelection的选项。请参阅http://ivaynberg.github.io/select2/#documentation

以下是initSelection选项的摘录。

// Or for single select elements:
$("#select").select2({
    initSelection : function (element, callback) {
        var data = {id: element.val(), text: element.val()};
        callback(data);
    }
});

这将指定默认值。