Get custom html attribute from <select> control using 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 gets called on page load:

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

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

      

As a result, I get "valp = undefined"

+3


source to share


4 answers


this

in context .change()

refers to <select>

, not to <option>

, so you don't get a node with an attribute valp

.

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

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

      



Here's a demo.

+6


source


The function change

provides you with the select

one that was updated instead of option

. You need to query the value :selected

. When you have the option selected, you can query the attributevalp

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

      



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

+2


source


Pass option

, not select

:

onChangeDropDownList1($(this).children(':selected'));

      

or, take the option from the past select

:

var vP = $($(obj).children(':selected')).attr('valp');

      

0


source


Just put JS code to the end of the body

0


source







All Articles