Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

215
Vistas
Cambiar la opción seleccionada por defecto dinámicamente

¿Cuál es el enfoque para cambiar la opción seleccionada predeterminada en un elemento de selección HTML? Espero que de alguna manera pueda combinarlo con una función de JavaScript que se activa cuando un usuario ingresa al sitio web.

Por ejemplo, si uno tiene lo siguiente que representa los primeros cuatro meses de un año (1 = enero, 2 = febrero, etc.) En el ejemplo, 1 siempre será el valor predeterminado seleccionado. ¿Pero es posible que el valor predeterminado sea 2 si el mes actual es 2 (=Feb) ?

Probablemente pueda obtener la hora actual usando la biblioteca moment.js , pero ¿se puede cambiar dinámicamente el valor seleccionado?

 <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 Respuestas
Responde la pregunta

0

Un enfoque sería el siguiente:

 // 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>

Referencias:

  • CSS:
    • Selectores de atributos .
  • JavaScript:
    • document.querySelector() .
    • EventTarget.addEventListener() .
    • Literales de plantilla .
about 4 years ago · Juan Pablo Isaza Denunciar

0

En esta variable, establezca su valor predeterminado como 2 o algo así como 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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda