Is it possible to use jQuery effects with the <option> tag of a <select>?

Asked

Viewed 57 times

0

I wanted to use a jQuery effect, for example the hide(). You can implement this effect by clicking on a <option>?

<div class="form-group" style="margin-left: 10px;margin-right:10px;width:50%;">
    <label>Selecione a categoria</label><br>
    <select class="form-control" name="categoria" id="cat" required>
        <option value="0" disabled selected hidden>Categoria</option>
        <option class="bt1">Impressão Digital (frente)</option>
        <option class="bt2" value="2">Impressão Digital (frente/verso)</option>
    </select>
</div>

In this case, my goal was that by clicking one of these <option> a certain <div> hide (using hide()).

I’ve tried using this jQuery code and it doesn’t work:

<script>
    $(document).ready(function() {
        $(".bt1").click(function() {
            $(".div1").siblings().hide();
        });
    });
</script>

2 answers

0

Hi, it is possible yes. Try something like:

<script>
    $(document).ready(function() {
        $(".cat").change(function() {
            if($(this).val() == 0){
               $(".div").siblings().hide();
            }
            if($(this).val() == 1){
               $(".div1").siblings().hide();
            }
            
        });
    });
</script>

Basically you take change of input value and based on it apply its logic

  • Hello Eduardo Worrel. I tried to solve my problem using your code but it didn’t work. Thanks anyway :)

-1


You can’t turn on the event click directly to option, but, it manages to take the option that was selected with the method find() and using the selector :Selected check if this is what you want, just give an Hide() in the div:

$(() => {
  $('#cat').on('click', function() {
    if($(this).find(":selected").hasClass('bt1')) $('.div1').toggle();
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="form-group" style="margin-left: 10px;margin-right:10px;width:50%;">
  <label>Selecione a categoria</label><br>
  <select class="form-control" name="categoria" id="cat" required>
    <option value="0" disabled selected hidden>Categoria</option>
    <option class="bt1">Impressão Digital (frente)</option>
    <option class="bt2" value="2">Impressão Digital (frente/verso)</option>
  </select>
</div>

<div class="div1" style="margin-top: 30px; background: #ccc">teste</div>

  • Hello Leandrade, I used your logic. The only problem I found is that after selecting other <option> and selecting a previously selected one again, it hid all the Ivs (including the one I want you to show. So I decided to just add the show() method into the code that presented and solved my problem. Thanks for the help :)

  • Nice that you helped Luis, success there!

Browser other questions tagged

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