javascript - 从单个下拉框中选择多个选项和值

标签 javascript html

我正在处理具有多个下拉选项的表单。

为了说明我的问题,我在下面的表格中将所有内容简化为三个问题。

我试过这段代码(以及一些变体):

function update_variables(el, standard_val, var_list) {
  standard_val.value = var_list[el.getElementsByTagName('option')[el.selectedIndex].value];
}

var select2 = document.getElementById('think_question'),
  hidden_answer = document.getElementsByName('thought_goes_here')[0];

var why_options = {
  'yes': '',
  'no': 'Well, you tried.'
};

select2.addEventListener('change', function() {
  update_variables(select2, hidden_answer, why_options);
});

var sel_group_control = document.getElementById('follower_question');
var sel_free_will = document.getElementById('think_question');


sel_group_control.addEventListener('change', answer_bypass);

function answer_bypass() {
  var user_choice = sel_group_control.value;
  if (user_choice === 'no') {
    sel_free_will.selectedIndex = 2;
    sel_free_will.style.backgroundColor = "#D3D3D3";
    sel_free_will.disabled = true;
  }
}
<h2>Life Decisions</h2>
<form>
  Be exactly like everone else?
  <select id='follower_question'>
    <option disabled selected value> -- select an option -- </option>
    <option>yes</option>
    <option>no</option>
  </select>
  <br> Think for yourself?
  <select id='think_question'>
    <option disabled selected value> -- select an option -- </option>
    <option>yes</option>
    <option>no</option>
  </select>
  <br> Original thought:<input name="thought_goes_here" size="50" value="" id="your_thoughts">
</form>

如果问题 2 设置为“否”,则问题 3 的答案是已知的,并填写了回复。如果问题 1 为“否”,则问题 2 应设置为“否”且只读。我希望在回答问题 1 选择“否”时,问题 3 也会自动更新,但该功能似乎被忽略了。

最佳答案

您需要注册一个事件来触发第二次选择更改。

像这样:

function answer_bypass() {
  var user_choice = sel_group_control.value;
  if (user_choice === 'no') {
    sel_free_will.selectedIndex = 2;
    sel_free_will.style.backgroundColor = "#D3D3D3";
    sel_free_will.disabled = true;

    // Create a new 'change' event
    var event = new Event('change');

    // Dispatch it.
    select2.dispatchEvent(event);
  }
}

关于javascript - 从单个下拉框中选择多个选项和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55579795/

相关文章:

javascript - Vue.js $scopedSlots 不适用于 Vue 实例

javascript - 在 HTML 表格中显示各种图像

android - 在某些手机中以整页显示的 Jquery 移动应用程序标题

java - 使用 Jsoup 提取和解析 HTML 表格

PHP 函数中的 javaScript 代码仅在第一次调用时有效

javascript - 点击图片后弹出网页上的视频播放

javascript - amCharts pie - 鼠标悬停在切片上时如何触发功能?

javascript - 在 ecmascript 6 中定义 setter 时出错

javascript - 使用选定的选项作为函数内的参数

html - section 标记在无序列表内还是周围?