Which event should I associate with select?

0

My script is not working, I just want to make the script display the paragraph when the select is selected, see:

$(document).ready(function()
  {
    $("#btn1").click(function(){
        $("p").hide();
    });
    $("#show").click(function(){
        $("p").show();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><p>Thisisaparagraph.</p><buttonid="btn1">Hide</button>
<select name="categoria" id="categoria">
   <option value="other">Other</option>
   <option value="show" id="show">Show</option>
</select>
    
asked by anonymous 12.09.2018 / 14:11

2 answers

3

You need to use the event change in select , not option .

So:

$(document).ready(function()
  {
    $("#btn1").click(function(){
        $("p").hide();
        $('#categoria').val("other");
    });
    $("#categoria").on('change', function(){

        this.value === "show" && $("p").show();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><p>Thisisaparagraph.</p><buttonid="btn1">Hide</button>
<select name="categoria" id="categoria">
   <option value="other">Other</option>
   <option value="show" id="show">Show</option>
</select>

The change does not fire when the value is already selected and you select it again. Therefore, in #btn1 I added the option that changes the value of select when it is clicked.

    
12.09.2018 / 14:26
3

You can use the change event of <select> and compare the selected value ( this.value ) is the desired value. From this you can hide or show your <p> .

Example:

var $paragrafo = $('#paragrafo');

$('#categoria').on('change', function () {
    $paragrafo.prop('hidden', this.value !== 'show');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="categoria">
    <option value="other">Other</option>
    <option value="show">Show</option>
</select>

<p id="paragrafo" hidden>Texto exemplo</p>
    
12.09.2018 / 14:21