Search code examples
jqueryselectedindex

Using jQuery to remove a class based on selectedIndex


Alright so I'm trying to remove a class based on a dropdown menu's selectedIndex, specifically, I want the div with the id=hide to appear when someone selects the second option in my dropdown menu (selectedIndex of 1), and disappear again if they select a different option.

Here is my html code:

<div id="product-variants">      
                <select id="product-select" name="id">

                        <option value="269270508">No Charm</option>

                        <option value="269270608">Heart (Add $25)</option>

                        <option value="269270614">Horseshoe Bead (Add $25)</option>

                        <option value="269270666">Crystal Horseshoe (Add $25)</option>

                        <option value="269270692">Cowgirl Cross (Add $25)</option>

                        <option value="269270732">Lucky Charm (Add $35)</option>

                        <option value="270460652">Round (Add $25)</option>

                        <option value="269270562">Small Star (Add $20)</option>

                        <option value="269270598">Large Star (Add $25)</option>
    </select>
</div>

<div id="hide" class="hidden"><form>
<input id="checkbox" type="checkbox" name="vehicle" value="Bike">Engraving?<br>
</form>
    <form>
Engraving Message: <input type="text" name="engraving"><br>
        </form></div>

My script:

var choice = getElementById("product-select").selectedIndex;

if (choice == 1){

    $('#checkbox').change(function(){
        $('#hide').removeClass('hidden');
    });

}

And CSS:

.hidden {
    display:none
}

And a link to it on jfiddle: http://jsfiddle.net/AFrjz/2/

I've been trying to figure this out for hours and just can't seem to do it.

Thanks so much!


Solution

  • try this

    if (choice == 1){
    
      //$('#checkbox').change(function(){ you are callinjg a change event here... so the hide is not fired..
        $('#hide').removeClass('hidden');
     // });
    
    }
    

    UPDATED

    I want the div with the id=hide to appear when someone selects the second option in my dropdown menu (selectedIndex of 1), and disappear again if they select a different option.

    i used the change event of the selectbox.. and checked the selected value.. if value is your second options's value.. then remove class else addclass

    $("#product-select").change(function(){
     var choice = $(this).val()
    
     if (choice == '269270608'){
    
    //$('#checkbox').change(function(){
        $('#hide').removeClass('hidden');  //remove class here
    //});
    
     }else{
        $('#hide').removeClass().addClass('hidden');  //else addclass
     }
    
    });
    

    fiddle here