JQuery 如何从表单中选择所选择的<option>

问题描述 投票:0回答:1

我想知道如何在我的 HTML 中只选择嵌套在我的标签中的同一类的所选元素:

<li>
  <select class="country"></select>
</li>

如果我使用

val()
函数,它只返回第一个元素,而如果我使用
text()
函数,它返回所有集合,因此会丢失用户选择的内容。

然后我需要将数据与另一个数据集合进行比较:

$.ajax({
  url: "../project1/php/countries.php",
  type: 'GET',
  dataType: 'json',
  success: function(res) {
    if (res) {
      let result = res.map((country) => {
        return country;
      })

      // creates a selector for each country in navbar
      for (let i = 0; i < result.length; i++) {
        let option = $("<option></option>", result[i].name).text(`${result[i].name}`).addClass("optionResult");
        $(".country").append(option);

      }
      // Once selectors are created, we can mark the borders when selector is clicked

      $('.optionResult').on('click', function() {
        let selectedCountry = $('.optionResutl').$(this).val();
        
        /// If select val() keeps returning Andorra
        console.log(selectedCountry, 'selected country var'); //seems to be fetching the selected country

        $.ajax({
          url: './countryBorders.geo.json',
          type: 'GET',
          dataType: 'json',
          success: function(borders) {
            console.log(borders);

            /// Loop through the borders and check if the selected country is selected
            /// Does not return the chosen country

            let input = [];
            borders.features.forEach((border) => {
              //Debug
              console.log('name in borders', border.properties.name);
              console.log('name in selectors', selectedCountry);

              // Nested forEach ?
              /*  if (border.properties.name == ) {
                    input.push(border);
                }; */
            })

            L.geoJSON(input, {
              style: function(feature) {
                return {
                  color: feature.properties.color
                };
              }
            }).bindPopup(function(layer) {
              return layer.feature.properties.description;
            }).addTo(map);
          },
          error: function(jqXHR, textStatus, errorThrown) {
            console.log(JSON.stringify(errorThrown));
          }
        })
      })
    }
  },
  error: function(jqXHR, textStatus, errorThrown) {
    console.log(JSON.stringify(errorThrown));
  }
});

我尝试使用 $(this) 选择器,但它会抛出一个错误,而且还没有找到其他解决方法。

谢谢你的帮助。

javascript html jquery
1个回答
1
投票

要获取

select
的选定值,您可以简单地检索它的
val()
。请注意,这是
select
的值,应该在
change
事件中检索,而不是孩子
click
value
option

const $countrySelect = $('.country');

// delegated event handler for selecting a country:
$countrySelect.on('change', function() {
  let selectedCountry = $(this).val();

  // send your AJAX request to get borders...
});

// populate country list via AJAX:
$.ajax({
  url: "../project1/php/countries.php",
  type: 'GET',
  dataType: 'json',
  success: function(res) {
    if (!res)
      return; // handle error, I assume?

    const optionsHtml = res.map(country => `<option value="${country}">${country}</option>`);
    $countrySelect.html(optionsHtml);
  },
  error: function(jqXHR, textStatus, errorThrown) {
    console.log(JSON.stringify(errorThrown));
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.