如何基于使用Javascript的父级答案为从属字段设置默认值? [英] How to set a default value for a dependent field based on the answer of the parent with Javascript?

查看:52
本文介绍了如何基于使用Javascript的父级答案为从属字段设置默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试有4个子字段,计费代码,渠道,主题代码和名称,根据其父字段Event Type的答案自动填充某些值.换句话说,如果事件类型的答案为"A",则将基于"A"为每个子字段显示一个下拉字段.

I'm trying to have 4 sub fields, billing code, channel, subject code and name, autopopulate certain values based on the answer of their parent field, Event Type. In other words, if the answer to event type is "A", dropdown fields will appear for each sub field based on "A".

推荐答案

比方说,文档的第一个选择元素具有值 植物",动物"和鬼魂"以及下一个选择元素应更改 当第一个元素的选定值更改时,我们将按照以下方式进行操作:

Let's say the first select-element of the document has the values 'Plant', 'Animal' and 'Ghost' and the next select-element should change when the selected value of first ele changes, then this is how we do it:

var majorField = document.getElementsByTagName('select')[0]
var minorField = document.getElementsByTagName('select')[1]

// Define a dict, mapping each possible value to a function:
majorField.onChangeMap = {
  Plant:  function() { minorField.innerHTML = '<option>Cocoa</option><option>Cocos</option>' },
  Animal: function() { minorField.innerHTML = '<option>Cat</option><option>Cow</option>' },
  Ghost:  function() { minorField.style.visibility = 'hidden' },
}
// When value changes, execute function of dict-map:
majorField.onchange = function(event) {
  event.target.onChangeMap[event.target.value]()
}

// Make sure he minor-field has initially the correct state, by
// executing the mapped function for the major-field's current-value:
majorField.onChangeMap[majorField.value]()

请注意,这只是一个非常简单的示例,仅用于映射,例如 一个人不会将选项设置为html字符串,并且将minorField隐藏在 在此处使用visibility = 'visible'的所有其他选项上,应将Ghost反转.

Note that this is a very minimal illustration-example for the mapping only, as one wouldn't set the options as an html-string, and hiding the minorField on Ghost should be reversed on all other options with visibility = 'visible', here.

这篇关于如何基于使用Javascript的父级答案为从属字段设置默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆