简体   繁体   English

通过select2将动态选择的内容分配给选项

[英]assign dynamically selected to option by select2

I try to add selected dynamically to select2 via php on returned get variable but I can't figure out how to do this. 我尝试通过返回的get变量上的php动态地将selected添加到select2,但是我不知道该怎么做。 I was trying the following but I suppose this needs to be done with jquery. 我正在尝试以下操作,但我想这需要通过jquery完成。 $grade is the retrived get varible $grade是获取的变量

<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>
<option value="<?php echo $index ?>" <?php if($index=="condition for adding selected"){echo "selected"} ?>
    <?php echo $a ?>
</option>

I don't know when you want to add "selected", but you can add selected dynamically like this. 我不知道何时要添加“选择的”,但是您可以像这样动态添加选择的。

I had a problem with this the other day, select2 has an option called initSelection . 前几天我对此有问题,select2有一个名为initSelection的选项。 See http://ivaynberg.github.io/select2/#documentation . 参见http://ivaynberg.github.io/select2/#documentation

Here is an extract for the initSelection option. 这是initSelection选项的摘录。

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

This will assign the default value. 这将分配默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM