问题
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