我有一个 select
,里面有 2 个选项,我的目标是根据所选选项显示/隐藏 html 元素。没有空选项,因此始终选择“默认”或“自定义”。
为此,我使用 jquery:
$(document).ready(function(){
$('.template-type').on('change', function() {
if ( this.value == 'default') {
$("#default_template").show();
$("#custom_template").hide();
} else {
$("#default_template").hide();
$("#custom_template").show();
}
});
});
但是当我重新加载页面时,无论保存的选项如何,两个 html 元素都再次可见,并且 this.options
的控制台日志告诉我它是 未定义
,但是重新加载后选择的选项与之前保存的选项匹配。
只有当我再次选择其他选项时,它才会按预期工作。
这是选择,一个 Symfony ChoiceType
字段,以防万一需要:
case 'email_category':
$attrFields = array('class' => 'form-control template-type');
$formFieldType = ChoiceType::class;
$optionFields = array('choices' => array('Default' => 'default', 'Custom' => 'custom'), 'choices_as_values' => true, 'label' => 'Type of template used:');
break;
最佳答案
假设您正在设置 selected
服务器端,您可以在声明更改处理程序后触发更改事件。
$(document).ready(function() {
$('.template-type').on('change', function() {
if (this.value == 'default') {
$("#default_template").show();
$("#custom_template").hide();
} else {
$("#default_template").hide();
$("#custom_template").show();
}
// trigger the change on page load
}).change();
});
关于jquery - 默认选择选项值未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57044346/