How to disable a combobox with a condition in jquery?

Asked

Viewed 1,397 times

3

I’m working on a project in Rails, where in a view of the project I own several combobox, where at first I would like only one to be enabled, and according to the value selected the others are released. I think it would be interesting to use Javascript or/with jQuery to do this, but I have little knowledge in both. Can someone tell me how to do it ? A light so I can follow ?

It’s code I tried, but it didn’t work:

var update_field = function () {
    if ($(".card") == 'Spell') {
        $('.cardFamily').prop('disabled', false);
    } else {
        $('.cardFamily').prop('disabled', 'disabled');
    }
};

$(update_field);

2 answers

2

To enable and disable a select you can use the codes below respectively:

With jQuery:

$('.cidades').prop("disabled", true);
$('.cidades').prop("disabled", false);

Javascript-enabled:

var cells = document.getElementsByClassName("cidades");

for (var i = 0; i < cells.length; i++) {
    cells[i].disabled = true; //ou false;
}

Now just put the same in your checks. Follow an example on jsfiddle.

1


First of all in hisif ($(".card") == 'Spell') is not testing the value of card, you must fetch the value, ie, if ($(".card").val() == 'Spell')


So you want when selecting an other combobox to be available.

$("#familia").change(troca);

function troca(){
  
  $(".familia").prop( "disabled", true );//desabilita todas opcoes
  
  var objetoSelecionado = $(this).val();//busca o valor o campo selecionado
  $("."+objetoSelecionado).prop("disabled", false); // habilita somente a selecionada.
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="familia">
  <option value ="">Nenhum</option>
  <option value ="souza">Souza</option>
  <option value ="silva">Silva</option>
</select>

<select class="familia souza" disabled>
 <option value ="">vazio</option>
 <option value ="maria">Maria Souza</option>
 <option value ="mario">Mario Souza</option>
</select>

<select class="familia silva" disabled>
 <option value ="">vazio</option>
 <option value ="maria">Maria silva</option>
 <option value ="mario">Mario silva</option>
</select>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.