Reputation: 606
I have a rather complicated lookup for an option. It comes from a separate system and I really need to keep track of two pieces of data instead of sending only one and having to do additional lookups which are expensive. Ideally, I want to pass all the data I received from one AJAX call into another.
Standard stuff:
<select name="chosen_option" id="chosen_option">
<option value="apple">Option One</option>
</select>
Accessing it with javascript is fairly simple:
$("#chosen_option).val()
I know I have many ways to put extra data into the option according to my searches:
<option value="PartA:'apple',PartB:'450'">Option One</option>
<option data-partb="450" value="apple">Option One</option>
For the first method I don't understand how to reference PartA or Partb on their own, only the entire value for the option.
For the second method the selector is not capable of grabbing that particular attribute from the selected option. It says undefined.
Adding an ID to each individual option does not allow me to grab it either:
<option id="optionid_apple" data-partb="450" value="apple">Option One</option>
$("#optionid_apple").attr('data-partb) // Not working
$("#optionid_apple").data('partb') // Not working
$("#optionid_apple").data('data-partb') // Not working
How can I store multiple pieces of data on a single option and access it in Javascript?
P.S - I thought about making the value itself an XML doc, but I don't really know how to do that correctly in the HTML, etc.
Upvotes: 2
Views: 1167
Reputation: 1746
Use this to make sure that you get the selected option.
$("#chosen_option option:selected").data('partb')
otherwise you are trying to get attributes from the <select>
tag.
Upvotes: 1