Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

209
Visualizações
Select field : get corresponding value of selected value

I have the following code :

 $(document).on("change", "[data-name=country] select", function () {     
    var country = $("[data-name=country] select").val();
    if (country != "") {
        $("[data-name=capital] input").val(country);
    } });

Of course, this code adds the country name to the "capital" field. I would like to create an array where I would indicate the capital city for each country, so ​as the capital is added to the field instead of the country.

I know this is a basic question, I wouldnt' have any problem to do that with PHP with an array, but I'm just beginning with javascript and I can't find the correct syntax.

Thank you very much !

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can declare a global object and use similarly to a php's associative array like this:

let countries = {
  'Country1': 'Capital1',
  'Country2': 'Capital2'
};

let countryName = 'Country1';

console.log(countries[countryName]);

EDIT:

Based on your example, you should first declare the countries object globally (outside of your document ready function) so that it is accessible from everywhere, including inside your function. Then since you have the country, you should try and get the capital from the object. Lastly, you should check if the capital variable contains a truthy value (not being, null, empty, undefined etc.), just in case you provide a country that you have not registered and proceed passing it to your element.

let countries = {
      'Country1': 'Capital1',
      'Country2': 'Capital2'
    };

$(document).on("change", "[data-name=country] select", function () {     
    let country = $("[data-name=country] select").val();
    let capital = countries[country];
    if (capital) {
        $("[data-name=capital] input").val(capital);
    } 
});
about 4 years ago · Juan Pablo Isaza Relatório

0

Here's a working example of what I think you're describing. Notice how you can grab the 'associative array' value for the chosen country:

countries[$(this).val()]

let countries = {
  'Australia': 'Canberra',
  'Switzerland': 'Bern'
};
$(document).ready(function() {
  for (let x in countries) $('select[name=countries]').append(`<option value='${x}'>${x}</option>`);
  $('form[data-name=country]').on("change", "select[name=countries]", function() {
   if ($(this).val()) $('.cap span').text(countries[$(this).val()])
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form data-name='country'>
  <select name='countries'><option></option></select>
  <hr>
  <div class='cap'>Capital: <span></span></div>
</form>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda