Which event should I associate with select?

Asked

Viewed 54 times

0

My script is not working, I just want to make the script display the paragraph when 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>This is a paragraph.</p>

<button id="btn1">Hide</button>
<select name="categoria" id="categoria">
   <option value="other">Other</option>
   <option value="show" id="show">Show</option>
</select>

2 answers

3

You can use the event change of <select> and compare if the selected value (this.value) is what you want. 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>

<select id="categoria">
    <option value="other">Other</option>
    <option value="show">Show</option>
</select>

<p id="paragrafo" hidden>Texto exemplo</p>

3


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

Thus:

$(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>This is a paragraph.</p>

<button id="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 again. Therefore, in #btn1 added the option that changes the value of select when it is clicked.

  • Why does it have 3 equal signs there? this.value === "show".

  • @Davidcesar there is no need in this case, but the three equal signs mean that you are checking the value and if it is of the same type. It is that in PHP and Javascript, there is difference between 1 == '1' and 1 === '1', both return different things. There is a question on the website about this.

  • You can explain this line to me: this.value === "show" && $("p"). show(); Vc used logical operators, I don’t understand.

  • @Davidcesar in Javascript, if the this.value === "show" is assessed as true, it passes to the next expression after &&, which is the $("p").show()

Browser other questions tagged

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