简体   繁体   中英

How to use Jquery to check class field on chosen select option?

I have some HTML with a form and a select option like the one below...

      <select id="typeofrequest" name="type">
        <option value="">PLEASE SELECT</option>
        <option value="email" class="color size font">Logo request</option>
        <option value="email">Image request</option>
...

I have some divs further down the page and SOME of them have the class of "size". So basically, when someone chooses "Logo request" (which has the class of "size") from the Select dropdown, I want that to trigger the other divs with class of "size" to appear/show (since they are display: none; to start).

if ($("#typeofrequest option").hasClass("size")) {
        $("div.size").show();
    }

However, with my current code, the divs with the class of "size" display no matter which select option I choose (ie if I chose "Image request" it still then reveals/shows the other divs. So clearly I'm not understanding something with how select and its options are read. Anyone see what I'm doing wrong?

Try using this:

  $('#typeofrequest').on( 'change', function( e ) {
      if( $(this).find('option:selected').hasClass("size") )
          $('div.size').show();
      else
          $('div.size').hide();
  });

JS Fiddle demo

You can try this:

    $(document).on('change', '#typeofrequest', function(){
        console.log($(this).find(':selected').val().hasClass('size'));
        if($(this).find(':selected').val().hasClass('size')){
            $("div.size").show();
        }else{
            $("div.size").hide();
        }
    });

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