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

你。 提交于 2019-12-08 15:55:42

问题


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]


回答1:


try alert(this.value)




回答2:


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



回答3:


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.




回答4:


You can try

alert(title.value)


来源:https://stackoverflow.com/questions/3597456/why-am-i-not-getting-the-value-from-onchange-with-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!