admin管理员组

文章数量:1323330

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"

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"

Share asked Mar 10, 2012 at 2:46 ahmd0ahmd0 17.3k36 gold badges144 silver badges236 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

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.

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/Jpfs3/

Pass the option, not the select:

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

or, grab the option from the passed select:

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

Just put the JS code before the end of the body

本文标签: javascriptGet custom html attribute from ltselectgt control with JQueryStack Overflow