NoReceipt4Panda NoReceipt4Panda - 5 months ago 18
jQuery Question

How to pull multiple attributes from one selected element?

Say for example I have

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


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

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

var $opt = $("select option:selected");
var str = "name=" + $opt.data("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?.