javascript - 调查问题需要根据家长回答显示和隐藏

标签 javascript jquery

我创建了这个 https://jsfiddle.net/jorden15/9yz45bz8/向您展示发生了什么。基本上我有一个调查生成器,它为这个调查创建 html,我正在处理的功能是根据 parent 的回答隐藏和显示子问题。

例如,如果您在第一个问题上选择是,则子问题应该会出现。我的问题是有四个问题很深,如果我在任何时候选择否,它都会显示最后一个问题。最后一个问题应该在 no 上触发,但仅作为其父项的结果而不是其他任何东西。

我认为这个问题与我的显示变量有关。由于单选按钮未定义,但我不确定该怎么做。

$(function(){
  $('body').on('change', '.parent_question select, .parent_question input', function(){
    var child_input = $('[name="' + $(this).data('child-name') + '"]');
    var child_question = child_input.closest('.survey_answers');
    var trigger_on = $(this).data('trigger-on');
    var show = $(this)[0].selectedIndex == undefined ? ($(this).closest('.survey_answers').find('input').index($(this)) + 1) == trigger_on : $(this)[0].selectedIndex == trigger_on;
    console.log(show);
    if (show) {
      child_question.show();
    } else {
      child_question.hide();
      if (child_input.val() != '' || child_input.is(':checked')) {
        child_input.val('');
        child_input.attr('checked', false);
        child_input.trigger('change');
      }
  }
  });
});

最佳答案

这解决了问题。问题是,如果答案发生变化,我试图在显示问题后隐藏问题,但我只是倒着做,它不喜欢那样。

$(function(){
  $('body').on('change', '.parent_question select, .parent_question input', function(){
    var child_input = $('[name="' + $(this).data('child-name') + '"]');
    var child_question = child_input.closest('.survey_answers');
    var trigger_on = $(this).data('trigger-on');
    var show = $(this)[0].selectedIndex == undefined ? ($(this).closest('.survey_answers').find('input').index($(this)) + 1) == trigger_on : $(this)[0].selectedIndex == trigger_on;
    console.log(show);
    if (show && (child_input.val() != '' || child_input.is(':checked'))) {
      child_question.show();
    } else {
      child_question.hide();
      child_input.val('');
      child_input.attr('checked', false);
      child_input.trigger('change');
  }
  });
});

关于javascript - 调查问题需要根据家长回答显示和隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34599047/

相关文章:

使用 array.reduce() 获取对象数组中对象出现次数的 JavaScript 代码

javascript - 在JavaScript中,表达式都是语句吗?

javascript - 使用处理函数更改 html 页面

javascript - jquery 计算字符数并添加类不起作用

javascript - 无法使用 gmaps.js 显示 map

javascript - jQueryUI 使用 $.ajax 从文本/csv 文件自动完成数据

javascript - 全局样式不起作用 - vue.js

javascript - 在 Javascript 中调用时类名不起作用?

javascript - select2.js 和 chosen.js 无法在下拉菜单中正确呈现

jquery - 使用 for 循环和 jquery 加载事件处理多个图像仅返回最后加载的一个 props