skip to Main Content

How are the buttons disabled from a specific list of values, in my situation?

I tried to do it like this:

    var pls = [[45], [1]];
    for(var el in pls){
        $.each($('.seat'), function(){
            var attr_el = $(this).attr("value");
            if(attr_el == el){
                $(this).prop("disabled",true);
            };
        });
    };
.seat{
  background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="seat" value="1">&nbsp;</button>
<button class="seat" value="45">&nbsp;</button>
<button class="seat" value="100">&nbsp;</button>

But only the 1 button is disabled, not the 45 button.

2

Answers


  1. Chosen as BEST ANSWER

    To solve the problem, I changed for...in on for...of, to take not indexes, but array values. Since we are working with an array inside an array, el is also an array with one element. So, we change el to el[0] to take the first (and only) argument.

        var pls = [[45], [1]];
        for(var el of pls){
            $.each($('.seat'), function(){
                var attr_el = $(this).attr("value");
                if(attr_el == el[0]){
                    $(this).prop("disabled",true);
                };
            });
        };
    .seat{
      background-color: green;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button class="seat" value="1">&nbsp;</button>
    <button class="seat" value="45">&nbsp;</button>
    <button class="seat" value="100">&nbsp;</button>


  2. No need to loop over the elements, you can use an attribute selector.

    var pls = [
      [45],
      [1]
    ];
    $.each(pls, (i, [el]) => 
      $(`.seat[value=${el}]`).prop('disabled', true)
    );
    .seat {
      background-color: green;
    }
    
    .seat:disabled {
      background-color: grey;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button class="seat" value="1">&nbsp;</button>
    <button class="seat" value="45">&nbsp;</button>
    <button class="seat" value="100">&nbsp;</button>

    I used destructuring in the callback argument list to extract the first element of each nested array in pls.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search