NoReceipt4Panda NoReceipt4Panda - 1 year ago 84
jQuery Question

How to pull multiple attributes from one selected element?

Say for example I have

<option id="4" data-name="tomato" data-length="six">Tomato</option>
<option id="5" data-name="onion" data-length="five">Onion</option>

I'm trying to call some javascript code later that will take those data-names and length for different variables:

var str = "name=" + jQuery("#data-name").val() + "&length=" + jQuery("#data-length").val();

How would I do this for multiple attributes from the same element?

Answer Source

You could access jQuery data-attributes with data() function:

var $opt = $("select option:selected");
var str = "name=" + $"name") + "&length=" + $data("length");

Or simply treating them as attributes:

var $opt = $("select option:selected");
var str = "name=" + $opt.attr("data-name") + "&length=" + $opt.attr("data-length");

This question may help you to understand the differences between these two approaches: jQuery Data vs Attr?.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download