Search code examples
javascriptjqueryif-statementselected

how do I write a jQuery/javascript if statement so that it's triggered when a html <option> with a specific class is selected?


<select>
  <option value='34'>Trees</option>
  <option value='13' class='create_sub_category'>Add new sub-category</option>
  <option value='24' class='create_sub_category'>Add new sub-category</option>
  <option value='57'>Cats</option>
  <option value='34' class='create_sub_category'>Add new sub-category</option>
</select>



<script type='text/javascript'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
if (selected(".create_sub_category")) {
  alert('hi');
}
</script>

Obviously, there's no such javascript or jQuery function called 'selected' that I used above in my if statement, but could someone help me find something that would do what I'm describing?


Solution

  • $('select').change(function() {
      if($('select option:selected').hasClass('create_sub_category')) 
      {
        alert("SELECTED");
      }  
    });
    

    You should put some id/class on that select element.