Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JQuery how to select the chosen <option> from a form

I was wondering how to select only the chosen element of the same class nested within my tag in my HTML:

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

If I use the val() function it returns only the first element, whereas if I use the text() function it returns all the collection hence losing what the user chose.

I need then to compare the data against another collection of data:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$.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));
  }
});

I tried to use the $(this) selector but it throws an error and have not found another way around this.

Thank you for your help.

>Solution :

To get the selected value of a select you can simply retrieve its val(). Note that this is the value of the select, which should be retrieved within the change event, not the click or value of the child 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));
  }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading