Can I pass a select value as a param to an onchange function? [duplicate]

浪尽此生 提交于 2019-12-23 03:25:17

问题


Is this possible using some combination of javascript and html?

<select onchange="myFunction(valueOfThisSelector)">
    <option value="op1">Op1</option>
    <option value="op2">Op2</option>
    <option value="op3">Op3</option>
</select>

I would prefer if the solution is achieved without using element ids, because I want to be able to apply this to many selectors. If the value reference can be achieved in the myFunction() script that is also an option, so long as it doesn't use document.getElementById().


回答1:


Just pass this as parameter, then get the value from it :

function myFunction(current_select){
    alert( current_select.value );
}
<select onchange="myFunction(this)">
    <option value="op1">Op1</option>
    <option value="op2">Op2</option>
    <option value="op3">Op3</option>
</select>

Or pass the value directly :

function myFunction(selected_value){
    alert( selected_value );
}
<select onchange="myFunction(this.value)">
    <option value="op1">Op1</option>
    <option value="op2">Op2</option>
    <option value="op3">Op3</option>
</select>


来源:https://stackoverflow.com/questions/40272039/can-i-pass-a-select-value-as-a-param-to-an-onchange-function

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