dcp3450
dcp3450

Reputation: 11187

Why am I not getting the value from onChange with Select?

Testing part of a form. So, right now I just want to alert what the user selects:

JS:

function getData(title)
{
     alert(title);
}

HTML generated by PHP:

<select name="currentList" onChange="getData(this);">
     <option value="hat">Hat</option>
     <option value="shirt">Shirt</option>
     <option value="pants">Pants</option>
</select>

when I change the value I get an alert with:

[object HTMLSelectElement]

Upvotes: 11

Views: 50024

Answers (4)

dennis23
dennis23

Reputation: 1

You can try

alert(title.value)

Upvotes: -1

BalusC
BalusC

Reputation: 1108632

With this you're passing the HTML select element to the function, not the value of the selected option. To obtain the value of the selected option, you need to get the selected option from the options by selectedIndex and then get its value. In a nutshell:

function getData(dropdown) {
    var value = dropdown.options[dropdown.selectedIndex].value;
    alert(value);
}

Upvotes: 12

Ian Davis
Ian Davis

Reputation: 19413

With jQuery, you could be concise with alert($("#currentList").val());, as long as you add the id="currentList" to the select list. This way you don't have to pass "this" to the onchange function.

Upvotes: 0

meder omuraliev
meder omuraliev

Reputation: 186562

try alert(this.value)

Upvotes: 19

Related Questions