jquery - 默认选择选项值未定义

标签 jquery

我有一个 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/

相关文章:

javascript - 悬停的最佳实践?

jquery - 如果 x 显示 x 如果 y 显示 y(我知道这个标题不好)

jquery - 如何使 JQuery 将 Ajax 响应视为纯文本而不是 JSON

javascript - 使用 mixitup.js 和 jQuery 隐藏选择列表中的选项

jquery - 如何使 fancybox 调整大小以自定义创建的 iframe 大小

jquery正则表达式否定字母

javascript - jQuery问题,jQuery接管页面上的所有链接

jquery - 如何激活 Bootstrap 模态背景?

jquery - 当 table 很大时,面板主体没有调整大小?

javascript - 在初始页面加载时加载目标 ajax php 文件