首页 > 解决方案 > 如何检查用户是否选择了一个属性 and add it to the search query? I'm getting JSON data from weather API. Currently my code gets town name from an html input and queries the API to get weather for that particular place. I have introduced a select element for count

问题描述

标签: javascriptjqueryapiselectdrop-down-menu

解决方案


我想你在找这个

$.getJSON("https://restcountries.eu/rest/v2/all", function(countryData) {
  var countryCodes = countryData.map(item => `<option value="${item.alpha2Code}">${item.name}</option>`);
  $("#country-select")
    .html('<option value="">Country</option>')
    .append(countryCodes.join(""));
})

$("#country-select").on("change", function() {
  console.log(this.value)
})

$("#weather-button").click(function() {
  $(".weather-img").html("");
  $(".weather-type").html("");
  $(".weather-temp").html("");

  var city = $("input[name=city-box]").val();
  var region = $("#country-select").val() || "whatever is default country code";

  $.getJSON("https://api.openweathermap.org/data/2.5/weather?q=" + city + region + "&units=metric&myapikey", function(data) {
    console.log(data);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id="country-select"></select>


推荐阅读