简体   繁体   中英

How to display an “alert” for an option to “selected” with a click using jquery and “ID”?

I have the following code in my html > body:

<select class="btntabla" id="opciones" style="height: 32px;">
    <option selected id="mostrartodo"       >Mostrar todo</option>
    <option          id="mostrargrafica"    >Mostrar solo gráfica</option>
    <option          id="mostrartabulacion" >Mostrar solo tabulación</option>
    <option          id="solografica"       >Ocultar solo gráfica</option>
    <option          id="solotabulacion"    >Ocultar solo tabulación</option>
</select>

I'm trying with jquery something like this in my html > head:

<script type="text/javascript" >
    $("#mostrartodo").click(function() {
          alert("hola");
    });
</script> 

I want to give you click on a "option" of "select" display an "alert"

How I can do that?

Listen to the change event on your select :

$('#opciones').on('change', function (event) {
    // Will always be triggered when the select changes ...
    alert('hola');
    // .. so you should check for the value
    // (please add some value attribute to your options)
    if ($(this).find('option:selected').val() === '1') {
      alert('HOLA');
    }
});
$("#opciones").on('change',function() {
       alert($(this).find("option:selected").text()+' clicked!');
});

Do like this... this is not a correct way to do...

$("#opciones").click(function() {
    var value = $(this).text(); 
    if (value == 'Mostrar todo'){
   alert('hola');
}
});

Hope this will work...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM