Updating of html element

Asked

Viewed 60 times

0

The code below

<div class="input-field">
   <select  id="ramal" multiple  name="ramal[]" >
     <option value="all" id="check-all" name="all" selected >Todas</option>
         <?php 
           if(count($ramais) > 0){
              foreach($ramais as $ramal){
                 formatRamal($ramal);
              }
           }
         ?>
   </select>
   <label>Tipo</label>
</div>



/*esta função encontra-se em outro arquivo*/
function formatRamal($ramal){
        echo "<option  class=\"check-ramal\" value=\"$ramal\">$ramal</option>";
    }

Form this select with multiple checkbox, which by default looks like this:

inserir a descrição da imagem aqui

My difficulty is to update the <option value="all" id="check-all" selected >Todas</option> to be unchecked when any other value is selected.

Unchecking until done, but does not update on the screen what was done with the following code.

$('#ramal').change(function() {

         if($('.check-ramal').is(":checked")){
            alert("um ramal espcifico foi selecionado");
            $('#check-all').removeAttr("selected");
            $('#check-all').update();
         }

      });

PS* I cannot comment on the answers, so I edit here to say that the answers below did not show the <option value="all" id="check-all" name="all" selected >Todas</option> unmarked.

But, it works the first time the page is loaded if just put like this:

<script>$('#check-all').removeAttr("selected"); </script>

But, I need the selection to be removed only when I select other values from the select and by default it is selected if no other value is checked.

  • Hi Ramos! You already have some answers. Next time put the HTML in the question. Just as you are forcing us to write by hand and we waste more time to help you. When you read this comment I will delete it. See you soon!

2 answers

0

And if you try like this:

$('#ramal').change(function() {
    var ramal = $('.check-ramal'),
        tudo = $('#check-all');
    if(ramal.is(':selected')){
        tudo.prop("selected", false);
        //console.log($('#ramal').val());
    }
});

0

You can do it like this:

$('#ramal').change(function() {
    var todas = this.querySelector('#check-all');
    var todasAtivo = this.querySelectorAll('option:checked').length == 1 && todas.selected;
    if (!todasAtivo) todas.selected = false;
});

This code checks if there is only one option chosen and if that option is #check-all. If this permission is not valid-select the #check-all.

jsFiddle: https://jsfiddle.net/1t7np93g/

Browser other questions tagged

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