jquery 在更改和加载时替换表单域

64jmpszr  于 2023-03-17  发布在  jQuery
关注(0)|答案(1)|浏览(84)

我的表单有两个字段,一个文本字段和一个下拉列表Countries。如果用户从下拉列表中选择United States,那么我将用一个下拉列表US States替换文本字段。

// Set Request Quote default Country to US
$('.ginput_address_country select option[value="US"]').attr("selected",true);

$(".ginput_address_country select").change(function(){
    var selectedCountry = $(this).children("option:selected").val();
    
    // Get original State form field
    var stateFieldID = $(this).closest('.ginput_complex').find('.ginput_address_state input, .ginput_address_state select').attr('id');
    
    if(selectedCountry == 'US') {

        $('#' + stateFieldID).replaceWith(
            '<select name="'+stateFieldID+'" id="'+stateFieldID+'" aria-required="false">' +
            '<option value="">Select State</option>' +
            '<option value="AL">Alabama</option>' +
                '<option value="AK">Alaska</option>' +
                '</select>');
        } else {
            $('#' + stateFieldID).replaceWith(
                '<input type="text" name="'+stateFieldID+'" id="'+stateFieldID+'" value="" aria-required="false">');
        }
    });
})

如果我想将下拉菜单设置为默认的美国,我如何在页面加载时触发更改,同时仍然保持更改事件?

2vuwiymt

2vuwiymt1#

我只是在change事件之后添加了$('.ginput_address_country select').val('US').trigger('change');

相关问题