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

216
Visualizações
Change default selected option dynamically

What is the approach for changing the default selected option in an HTML select element? I expect that I somehow can combine it with a javascript function that is triggered when a user enters the website.

For example, if one has the following representing the first four months of a year (1=Jan, 2=Feb etc.) In the example, 1 will always be the default selected value. But it is possible to have the default value to be 2 if the current month is 2 (=Feb)?

I can probably get the current time using the moment.js library, but can the selected value be changed dynamically?

<body>
    <select id="month", onchange="setMonth();">
        <option value='1' selected>1</option>
        <option value='2'>2</option>
        <option value='3'>3</option>
        <option value='4'>4</option>
    </select>

    <script>
        var monthValue = month.options[month.selectedIndex].value.padStart(2, '0');

        function setMonth() {
            monthValue = month.options[month.selectedIndex].value.padStart(2, '0');
        }
    </script>

</body>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

One approach would be as follows:

// modifying the DOM once the DOM has been loaded, using EventTarget.addEventListener()
// to listen for the 'DOMContentLoaded' event, and and then modifying the DOM in the anonymous
// Arrow function:
window.addEventListener('DOMContentLoaded', (e) => {
  // create a new Date, which defaults to returning the date of the current 'today':
  let date = new Date(),
    // we then use the getUTCMonth() to retrieve the number of the current month, in
    // the range of 0 (January) to 11 (December); we therefore add 1 to reflect the
    // value: month pairing in the HTML:
    currentMonth = date.getUTCMonth() + 1,
    // here we use document.querySelector() to return the first matching element
    // in the document that matches the selector; the selector is a template-
    // literal string which allows us to interpolate JavaScript into the string,
    // which we do to create a CSS attribute-selector:
    opt = document.querySelector(`#month option[value="${currentMonth}"]`);
  // we then set the 'selected' property of that node to true:
  opt.selected = true;
  // and the defaultSelected value to true:
  opt.defaultSelected = true;
});
<!-- note the removal of the inline event-handling; in which the
     default was selected only on interaction; this has been moved
     to the JavaScript section, where it happens on the
     DOMContentLoaded event: -->
<select id="month">
  <option value="1">January</option>
  <option value="2">February</option>
  <option value="3">March</option>
  <option value="4">April</option>
  <option value="5">May</option>
  <option value="6">June</option>
  <option value="7">July</option>
  <option value="8">August</option>
  <option value="9">September</option>
  <option value="10">October</option>
  <option value="11">November</option>
  <option value="12">December</option>
</select>

References:

  • CSS:
    • Attribute selectors.
  • JavaScript:
    • document.querySelector().
    • EventTarget.addEventListener().
    • Template literals.
about 4 years ago · Juan Pablo Isaza Relatório

0

In this variable set your default value like 2 or something like defaultMonth

<select id="month", onchange="setMonth();" value="defaultMonth">
    <option value='1' selected>1</option>
    <option value='2'>2</option>
    <option value='3'>3</option>
    <option value='4'>4</option>
</select>
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