how to save data in html for onchange script?
I have two select's. The values/text of the second one will vary based on what is selected in the first select.
I will have onchange function linked to the first select. But I do not kno开发者_运维技巧w
- how I can save data for my onchange function in html
- how I can change second select html definition (text/values + number of options) in my javascript code
Note that I don't want to use any javascript framework
1) I assume you're seeking advice on how to encode the data for the second select input. I suggest using JavaScript to store a mapping of possible values of the first select to value to be used by the second so you can index it directly, e.g.:
// Assume "select1" can have option values "English" and "Spanish".
var select2data = {
'English': [['One', 1], ['Two', 2], ['Three', 3]],
'Spanish': [['Uno', 1], ['Dos', 2], ['Tres', 3]]
};
This strategy is nice concise but requires programmatic generation of JavaScript. If you really want to use plain HTML then you could have a nested DIV structure and parse it as needed, e.g.:
<div id="select2data" style="display:none">
<div id="English">
<div><div>One</div><div>1</div></div>
<div><div>Two</div><div>2</div></div>
...
<div id="Spanish">
...
<script type="text/javascript">
var s2d = document.getElementById("select2data")
, select2data = {};
for (var i=0; i<s2d.children.length; i++) { // Each of "id=English", etc.
var data=s2d.children[i], opts=[];
for (var j=0; j<data.children.length; j++) {
opts.push(new Option(data.children[j].children[0].firstChild,
data.children[j].children[1].firstChild));
}
select2data[data.id] = opts;
}
</script>
2) Now, setting the options of select2 can be done by looking up the data from the value of select1, encoding them as DOM Option objects, and adding them to select1:
var sel1 = document.getElementById('select1')
, sel2 = document.getElementById('select2');
sel1.onchange = function() {
var os = select2data[sel1.value]; // Get the options required by select1.
if (os) {
sel2.options.length = 0; // Clear the options for select2.
for (var i=0; i<os.length; i++) {
var o = new Option(os[i][0], os[i][1]);
try { // Add each option, allowing for browser differences.
sel2.add(o);
} catch (ex) {
sel2.add(o, null);
}
}
sel2.selectedIndex = 0;
}
return true;
};
Note that this is all untested and has lots of room for improvement but should illustrate the idea.
I think http://dev.w3.org/html5/spec/elements.html#embedding-custom-non-visible-data-with-the-data-attributes answers your question.
A custom data attribute is an attribute in no namespace whose name starts with the string "data-", has at least one character after the hyphen, is XML-compatible, and contains no characters in the range U+0041 to U+005A (LATIN CAPITAL LETTER A to LATIN CAPITAL LETTER Z).
...
Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.
精彩评论