Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]

like image 580
dcp3450 Avatar asked Aug 30 '10 02:08

dcp3450


People also ask

Can I use Onchange in select tag?

yes it's simple in javascript.

Why is Onchange not working?

onchange is not fired when the value of an input is changed. It is only changed when the input's value is changed and then the input is blurred. What you'll need to do is capture the keypress event when fired in the given input. Then you'll test the value of the input against the value before it was keypressed.


1 Answers

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);
}
like image 179
BalusC Avatar answered Oct 23 '22 07:10

BalusC