NoReceipt4Panda NoReceipt4Panda - 4 months ago 6x
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');