Voltaki
Voltaki

Reputation: 113

Run javascript code if specific select options are chosen

I need to have multiple state codes as conditional options not just "C". But i don't need all of the options, because this code should appear only with some of the options, not all.

So where it says var stateCode = 'C'; i need to have something like: 'C','D','G','K'.

Thanks!

<script>
    jQuery(document).ready(function($){

        // Set the state code (That will display the message)
        var stateCode = 'C';

        $('select#billing_state').change(function(){

            selectedState = $('select#billing_state').val();

            if( selectedState == stateCode ){
                $('.shipping-notice').show();
            }
            else {
                $('.shipping-notice').hide();
            }
        });

    });
</script>

Update: Here is the html code.. with only 3 options as example. I need the code to work only with option C and B but not K.

<select name="billing_state" id="billing_state" class="state_select select2-hidden-accessible" autocomplete="address-level1" data-placeholder="Elige una opción…" data-input-classes="" tabindex="-1" aria-hidden="true">

<option value="">Select an option</option>
<option value="C">Ciudad Autónoma de Buenos Aires</option>
<option value="B">Buenos Aires</option>
<option value="K">Catamarca</option>

</select>

Upvotes: 0

Views: 78

Answers (1)

Satvik Daga
Satvik Daga

Reputation: 156

You can have an array of all the options for which you want the code to work. Then you can check whether the selected option is correct using Array.includes.

<script>
    jQuery(document).ready(function($){

        // Set the state code (That will display the message)
        var stateCodes = ['C', 'B'];

        $('select#billing_state').change(function(){

            selectedState = $('select#billing_state').val();

            if(stateCodes.includes(selectedState)){
                $('.shipping-notice').show();
            }
            else {
                $('.shipping-notice').hide();
            }
        });

    });
</script>

Hope this helps.

Upvotes: 2

Related Questions