Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get custom html attribute from <select> control with JQuery

I was wondering what am I doing wrong here?

I have the following HTML:

<select name="somename" id="DropDownList1">
    <option value=""></option>
    <option value="1" valp="7700000000000000">Item 1</option>
    <option value="2" valp="7C08000000000000">Item 2</option>
    <option value="3" valp="5800000000000000">Item 3</option>
</select>

And the following JS/JQuery code that is called when the page loads:

$('#DropDownList1').change(function () {
    onChangeDropDownList1(this);
});

function onChangeDropDownList1(obj) {
    var vP = $(obj).attr('valp');
    alert("valp=" + vP);
};

As the result I get "valp=undefined"

like image 876
ahmd0 Avatar asked Mar 19 '26 15:03

ahmd0


2 Answers

this in context of the .change() refers to the <select> rather than the <option>, so you're not getting the node with the valp attribute.

$('#DropDownList1').change(function () {
    onChangeDropDownList1(this);
});

function onChangeDropDownList1(obj) {
    // Get the selected option
    var vP = $(obj).find(':selected').attr('valp');
    alert("valp=" + vP);
};

Here is a demonstration.

like image 148
Michael Berkowski Avatar answered Mar 21 '26 05:03

Michael Berkowski


The change function is providing you the select which was updated not the option. You need to query the :selected value out of it. Once you have the selected option you can query for the valp attribute

function onChangeDropDownList1(obj) {
    var vP = $(obj).find('option:selected').attr('valp');
    alert("valp=" + vP);
};

Fiddle: http://jsfiddle.net/Jpfs3/

like image 24
JaredPar Avatar answered Mar 21 '26 03:03

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!