1 votes

How to disable options by means of a class?

I have created a function to try to disable options from certain selects ; I just can't do it. This function does bring me the options that I need to disable, but when assigning disabled to the elements nothing happens.

 const desabledFields = (clase) => {
  let campos = [...document.getElementsByClassName(clase)];
  campos = campos.filter((elem) => elem.type == "select-one");
  campos.forEach((campo) => {
    [...campo.options].forEach((option) => (option.disabled = true));
  });
  jQuery(`.${clase}`).prop("readonly", true);
};

jQuery(document).ready(() => {
  desabledFields("read");
});

1voto

jdromero88 Points 383

 //el primer campo no va a desactivar porque tiene la clase diferente.
const desactivarCampos = () => {
  // obtenes todos los campos que tengan la clase texto
  let campos = document.getElementsByClassName('texto')
  // si imprimis campos te muestra que tenes un objeto de key value.
  // console.log(campos)
  // recorres tu objeto y le agregas disabled.
  for (const [key, value] of Object.entries(campos)) {
    //console.log(`${key}: ${value.value}`);
    value.setAttribute('disabled', 'true')
  }
}
document.addEventListener('DOMContentLoaded', (event) => {
    desactivarCampos()
});
 .texto{
  color:red;
}
 <input type="text" class="texto-sin-desactivar" >
<input type="text" class="texto" >
<input type="text" class="texto" >
<input type="text" class="texto" >
<input type="text" class="texto" >

I hope it serves as a guide. Greetings.

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X