How to set a default value for a dependent field based on the answer of the parent with Javascript?

吃可爱长大的小学妹 提交于 2019-12-22 16:09:28

问题


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".


回答1:


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]()

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.



来源:https://stackoverflow.com/questions/44460525/how-to-set-a-default-value-for-a-dependent-field-based-on-the-answer-of-the-pare

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!