3

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"

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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/

Comments

0

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');

Comments

0

Just put the JS code before the end of the body

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.