更改选择可见值,同时下拉文本保持不变

问题描述 投票:0回答:1
javascript html jquery
1个回答
0
投票

您可以通过将选择中所选文本的显示与下拉菜单中的实际文本分开来解决这个问题,其想法是仅更改选择后的可见文本,而不更改下拉菜单中选项的内容-向下菜单。

1- 使用 div 或类似的 HTML 标签显示“排序方式:”格式的文本,后跟所选值,而不更改下拉菜单中选项的显示。

2- 保持选择选项不变,并使用 JavaScript 调整可见文本。

试试这个:

<?php
    $option_select = function($opt_val) {
        if($opt_val == $_GET["order"]) {
            echo "selected";
        }
    };
?>

<form name="sort" id="sort" action="matches.php" method="get" style="float:right; margin:10px;">
    <div id="selectedText">Sort by: Last online</div> <!-- Div pour afficher le texte formaté -->
    
    <select name="order" id="order" class="order_select" onchange="changeSort()">
        <option <?php $option_select("last_online"); ?> value="last_online">Last online</option>
        <option <?php $option_select("age_asc"); ?> value="age_asc">Age (Young to Old)</option>
        <option <?php $option_select("age_desc"); ?> value="age_desc">Age (Old to Young)</option>
        <option <?php $option_select("height_asc"); ?> value="height_asc">Height (Short to Tall)</option>
        <option <?php $option_select("height_desc"); ?> value="height_desc">Height (Tall to Short)</option>
        <option <?php $option_select("created_asc"); ?> value="created_asc">Date subscribed (New to Old)</option>
        <option <?php $option_select("created_desc"); ?> value="created_desc">Date subscribed (Old to New)</option>
    </select>
    <input type="submit" value=" Sort " class="btn btn-info" hidden />
</form>

<script>
document.addEventListener("DOMContentLoaded", function() {
    var orderSelector = document.getElementById("order");
    var selectedText = document.getElementById("selectedText");

    // Update the displayed text on load
    updateSortText(orderSelector);

    // Function to update the displayed text
    function updateSortText(selector) {
        var selectedOption = selector.options[selector.selectedIndex].text;
        selectedText.textContent = "Sort by: " + selectedOption;
    }

    function changeSort() {
        updateSortText(orderSelector);
        var orderForm = document.getElementById("sort");
        orderForm.submit();
    }

    orderSelector.addEventListener('change', function() {
        updateSortText(this); // Updates text on selection
    });
});
</script>
© www.soinside.com 2019 - 2024. All rights reserved.