如果选择了特定的选择选项,请运行javascript代码

时间:2020-03-07 18:57:57

标签: javascript jquery

我需要有多个状态代码作为条件选项,而不仅仅是“ C”。 但是我不需要所有选项,因为此代码应仅与某些选项一起出现,而不是全部。

所以说var stateCode = 'C';的地方我需要像这样:'C','D','G','K'

谢谢!

<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>

更新: 这是html代码..仅以3个选项为例。 我需要代码仅适用于选项C和B,而不适用于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>

1 个答案:

答案 0 :(得分:2)

您可以拥有一个所有要使用代码的选项的数组。 然后,您可以使用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>

希望这会有所帮助。

相关问题