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

158
Vistas
botones javascript ¿cómo elimino una clase de todos los botones cuando se selecciona un valor determinado?

Tengo un par de botones con un botón que debería desactivar todos los demás. Escribí un código que selecciona botones al agregar una clase y cuando se vuelve a hacer clic, se elimina la clase. También empujó el valor a una matriz. Quiero hacer que el botón sin preferencia en mi código elimine una determinada clase de todos los botones, excepto el botón sin preferencia.

Ya lo hice, por lo que elimina todo en la matriz cuando se hace clic en él, pero solo tengo que eliminar la clase de todos los botones.

Código:

 let div = document.getElementById('buttonDiv'); let arr = []; div.addEventListener("click", function (event) { let tgt = event.target; function SelectedClass() { if (tgt.classList.contains('Selected')) { tgt.classList.remove('Selected'); } else { tgt.classList.add('Selected'); } } if (tgt.classList.contains('buttons')) { if (arr.indexOf(tgt.value) === -1) { if (tgt.value === 'Ignore') { if (tgt.classList.contains('Selected')) { tgt.classList.remove('Selected'); } else { tgt.classList.add('Selected'); arr = []; } } else { SelectedClass(); arr.push(tgt.value); } } else { arr.splice(arr.indexOf(tgt.value), 1); SelectedClass(); } } console.log(arr); })
 .buttondiv { position: relative; width: 200px; height: 675px; margin-left: 50%; transform: translateX(-50%); margin-top: 50px; } .buttons { width: 275px; height: 50px; display: inline-block; margin-bottom: 15px; ; border: 2px solid black; border-radius: 3px; background-color: white; color: black; } .Selected { background-color: orangered; color: white; border: none; }
 <div class="buttondiv" id="buttonDiv"> <button value="btn1" class="buttons">1</button> <button value="btn2" class="buttons">2</button> <button value="btn3" class="buttons">3</button> <button value="btn4" class="buttons">4</button> <button value="Ignore" class="buttons">No Preference</button> </div>
Intenté hacerlo con un bucle for y un selector de consulta, pero no funcionó. ¿Alguien sabe una solución?

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Como puede ver en mi ejemplo, agrego un querySelectorAll a todos los botones, excepto al botón de ignorar, cuando el usuario hace clic en "Sin preferencia" forEach se deshabilitará o habilitará todo.

 let div = document.getElementById('buttonDiv'); let arr = []; div.addEventListener("click", function(event) { let tgt = event.target; function SelectedClass() { if (tgt.classList.contains('Selected')) { tgt.classList.remove('Selected'); } else { tgt.classList.add('Selected'); } } if (tgt.classList.contains('buttons')) { if (arr.indexOf(tgt.value) === -1) { if (tgt.value === 'Ignore') { if (tgt.classList.contains('Selected')) { tgt.classList.remove('Selected'); document.querySelectorAll('button:not(.ignore)').forEach(el => { el.disabled = false; }); } else { tgt.classList.add('Selected'); document.querySelectorAll('button:not(.ignore)').forEach(el => { if (el.classList.contains('Selected')) { el.classList.remove('Selected'); } el.disabled = true; }); arr = []; } } else { SelectedClass(); arr.push(tgt.value); } } else { arr.splice(arr.indexOf(tgt.value), 1); SelectedClass(); } } console.log(arr); })
 .buttondiv { position: relative; width: 200px; height: 675px; margin-left: 50%; transform: translateX(-50%); margin-top: 50px; } .buttons { width: 275px; height: 50px; display: inline-block; margin-bottom: 15px; ; border: 2px solid black; border-radius: 3px; background-color: white; color: black; } .Selected { background-color: orangered; color: white; border: none; }
 <div class="buttondiv" id="buttonDiv"> <button value="btn1" class="buttons">1</button> <button value="btn2" class="buttons">2</button> <button value="btn3" class="buttons">3</button> <button value="btn4" class="buttons">4</button> <button value="Ignore" class="buttons ignore">No Preference</button> </div>

Referencia:

  • Documento.querySelectorAll()
  • desactivado
about 4 years ago · Santiago Trujillo Denunciar

0

Si te entiendo correctamente, el código se puede simplificar. Vea el ejemplo a continuación donde se llevan a cabo diferentes acciones según el clima que presione el botón sin preferencia u otro botón. Para esto, agregué una clase al botón sin preferencia para que podamos consultarlo fácilmente.

 let div = document.getElementById('buttonDiv'); let arr = []; div.addEventListener("click", function (event) { let tgt = event.target; if (tgt.classList.contains('buttons')) { //when no preference is clicked remove all selected classes and empty the array if(tgt.value === 'Ignore') { event.currentTarget.querySelectorAll('.buttons').forEach((el) => { el.classList.remove('Selected'); arr = []; }); } //when other button is clicked removed the selected class from the no preference button and push the current value to the array else { event.currentTarget.querySelector('.buttons.ignore').classList.remove('Selected'); arr.push(tgt.value); } //always add selected class to the current button. tgt.classList.add('Selected'); } console.log(JSON.stringify(arr)); })
 .buttondiv { position: relative; width: 200px; height: 675px; margin-left: 50%; transform: translateX(-50%); margin-top: 50px; } .buttons { width: 275px; height: 50px; display: inline-block; margin-bottom: 15px; ; border: 2px solid black; border-radius: 3px; background-color: white; color: black; } .Selected { background-color: orangered; color: white; border: none; }
 <div class="buttondiv" id="buttonDiv"> <button value="btn1" class="buttons">1</button> <button value="btn2" class="buttons">2</button> <button value="btn3" class="buttons">3</button> <button value="btn4" class="buttons">4</button> <button value="Ignore" class="buttons ignore">No Preference</button> </div>

about 4 years ago · Santiago Trujillo 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