NoReceipt4Panda NoReceipt4Panda - 2 years ago 53
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?

Answer Source

$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');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download