Reputation: 97
Similar question to Can an Option in a Select tag carry multiple values? - except I want to reference the values in JavaScript
To recap:
I want to return more than one value for a selected item in a selectbox - so I was thinking something like this:
<SELECT id='selectList'>
<OPTION value1="a" value2="b" value3="c">OPTION 1</OPTION>
<OPTION value1="d" value2="e" value3="f">OPTION 2</OPTION>
</SELECT>
I then want to get the values of the selected item:
var sel = document.getElementById('selectList');
selValue1 = sel.options(sel.selectedIndex).value1;
selValue2 = sel.options(sel.selectedIndex).value2;
selValue3 = sel.options(sel.selectedIndex).value3;
currently I can pull value='x' for an option but I need more values to be associated with the option. I could probably delimit all three values into one and later use string functions to split them out, but that just seem nasty.
Upvotes: 3
Views: 1908
Reputation: 44906
I think you are looking for the attributes property:
var sel = document.getElementById('selectList');
selValue1 = sel.options[sel.selectedIndex].attributes.value1.value;
Here is a jsFiddle demonstrating how to extract these values.
Upvotes: 3
Reputation: 161
I would put all values inside an array of objects in JS and refer each position of that array as the value the OPTIONS in SELECT element.
So, my SELECT would be something like that (value = index position of the array):
<SELECT id='selectList'>
<OPTION value="0">OPTION 1</OPTION>
<OPTION value="1">OPTION 2</OPTION>
</SELECT>
And an example of array:
var array = [
{
"value1": "a",
"value2": "b",
"value3": "c"
},
{
"value1": "d",
"value2": "e",
"value3": "f"
}
];
array[0]
Object {value1: "a", value2: "b", value3: "c"}
array[1]
Object {value1: "d", value2: "e", value3: "f"}
And how you could get each object:
var sel = document.getElementById('selectList');
var selectedValue = sel.options[e.selectedIndex].value;
When selected value is first option (value = 0):
array[selectedValue]
Object {value1: "a", value2: "b", value3: "c"}
array[selectedValue].value1
"a"
array[selectedValue].value2
"b"
When selected value is first option (value = 1):
array[selectedValue].value1
"d"
array[selectedValue].value2
"e"
and so on...
Upvotes: 0
Reputation: 5676
Couldn't understand the reason for that. Of course you could use custom data attributes like https://developer.mozilla.org/en-US/docs/HTML/Global_attributes#attr-data-* or simply plain old get/setAttribute().
A better solution would be, to make an Object like
var optionValues={ option1: [a,b,c], option2 [d,e,f] }
so the resolution of the array is easy as pie:
var values=optionValues[selectedOption];
So there is no need to store additional data in the DOM.
Upvotes: 0