NoReceipt4Panda NoReceipt4Panda - 5 months ago 11
Javascript Question

Get attributes from a selected element in dropdown?

If I have this HTML code:

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


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

$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 = $selectedValue.data('name');
Comments