开发者

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

开发者 https://www.devze.com 2023-01-13 20:45 出处:网络
Testing part of a form. So, right now I just want to alert what the user selects: JS: function getData(title)

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>
<开发者_JS百科;/select>

when I change the value I get an alert with:

[object HTMLSelectElement]


try alert(this.value)


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


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.


You can try

alert(title.value)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号