如何使用 JavaScript 获取 AJAX 的 select 值

How to get select value for AJAX using JavaScript

我有 2 个 HTML 下拉菜单。

<div class="bar-option">
    <label>Filter:</label>
    <form>
        <select name="retreat_locations" onchange="filterRetreats(this.value, 'count(reviews.retreat_id)')">
            <option value="alllocations" selected="selected">All Locations</option>
            <?php foreach ($this->locations as $location) {?>
            <option value="<?=htmlentities($location->retreat_location);?>">
                <?=htmlentities($location->retreat_location);?> </option>
            <?php }?>
        </select>
    </form>
</div>
<div class="bar-option">
    <label>Sort by:</label>
    <select onchange="filterRetreats('alllocations', this.value)">
        <option selected='selected' value='retreat_number_of_reviews'>Popularity</option>
        <option value='retreat_founded_in'>Age</option>
        <option value='total_review_cost'>Cost</option>
    </select>
</div>

从上面可以看出,第二个select使用静态值'alllocations'作为onchange函数的第一个参数。

如何用第一个下拉列表 (retreat_locations) 的 selected 选项替换此静态值?

我尝试了 retreat_locations.value 但没有用。

感谢任何帮助。

您可以使用:

document.querySelector('[name=retreat_locations]').value

您的代码将变为:

filterRetreats(document.querySelector('[name=retreat_locations]').value, this.value)

演示:

function filterRetreats(value1, value2) {
  console.log(value1, value2);
}
<div class="bar-option">
                    <label>Filter:</label>
                    <form>
                        <select name="retreat_locations" onchange="filterRetreats(this.value, 'count(reviews.retreat_id)')">
                            <option value="alllocations" selected="selected">All Locations</option>
                            <option value="2">2</option>
                        </select>
                    </form>
                </div>
                <div class="bar-option">
                    <label>Sort by:</label>
                    <select onchange="filterRetreats(document.querySelector('[name=retreat_locations]').value, this.value)">
                        <option selected='selected' value='retreat_number_of_reviews'>Popularity</option>
                        <option value='retreat_founded_in'>Age</option>
                        <option value='total_review_cost'>Cost</option>
                    </select>
                </div>

其他 -old school- 选项是在第一个 select 上添加一个 id 标签,例如id="retreat_locations" 并使用 document.getElementById('retreat_locations').value.