在当前选择的选项之前获取选择框选项

时间:2018-07-26 01:53:09

标签: jquery select drop-down-menu

我有一个选择框,该框将用于某些后端排序。下面,通过将要排序的项目放在中间,将当前选择的项目(在此方案中)放在后面,来直观地表示新订单的外观。

我需要一种方法来获取上一个选项的文本(因此该选项直接位于当前选定的选项之前),以便可以填充前一项的文本。我该怎么办?

<p>Select an item in the following list that you want this item to go <i>before</i>.</p>
<select name="order-list" id="order-list" class="form-control">
    {array_to_select($list)}
</select>
<p class="m-t-md">Presentation order after changes:</p>
<ul class="list-group">
    <li class="list-group-item" id="sortable-item-before">Before Item</li>
    <li class="list-group-item" id="sortable-item-current">{$current_item}</li>
    <li class="list-group-item" id="sortable-item-after">After Item</li>
</ul>
<script>
    $(document).ready(function () {
        var before = $('#sortable-item-before');
        var after = $('#sortable-item-after');
        $('#order-list').on('change', function (e) {
            e.preventDefault();
            after.html($(this).find('option:selected').text());
        });
    });
</script>

示例列表选项:

<option value="68">Some option</option>

**值不能假定是连续的。

1 个答案:

答案 0 :(得分:0)

获取所选选项的索引,从中减去1,然后使用它来获取前一个选项。

var index = this.selectedIndex;
if (index > 0) {
    var prevOption = $(this).find("option").eq(index-1);
} else {
    prevOption = null;
}