J. Rorie J. Rorie - 1 month ago 7
Javascript Question

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

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()
.

Answer

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>

Comments