NoReceipt4Panda NoReceipt4Panda - 9 months ago 19
HTML Question

How to grab attributes from a selected value in a dropdown?

If I have this HTML code:

<select id="selectSomething">
<option id="4" data-name="tomato" data-email="">Tomato</option>
<option id="5" data-name="potato" data-email="">Potato</option>

And someone picks an option..

I then have this javascript code:

var $selectedValue = $("#selectSomething option:selected");
var somethingName = $selectedValue("data-name");
var somethingEmail = $selectedValue("data-email");

But for some reason I get an error: "Uncaught TypeError: $selectedValue is not a function"

What's wrong here, and how do I get this to work?


$selectedValue is a jQuery selector element. Getting a property out of this can be done with

var somethingName = $selectedValue.attr('data-name');

but in your case, it might be more appropriate to use .data() which is specifically invented for data- attributes

var somethingName = $'name');