简体   繁体   中英

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>

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.

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