In the traditional way to add event listener:
function getComboA(sel) {
var value = sel.options[sel.selectedIndex].value;
}
<select id="comboA" onchange="getComboA(this)">
<option value="">Select combo</option>
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
<option value="Value3">Text3</option>
</select>
But I wanted to adapt to the addEventListener way:
productLineSelect.addEventListener('change',getSelection(this),false);
function getSelection(sel){
var value = sel.options[sel.selectedIndex].value;
alert(value);
}
It doesn’t work because I can’t pass any parameter in getSelection() as the second parameter in addEventListener method? As far as I know I can only use the function name without parenthesises.
Any idea?
BTW, please look at my previous question about console.log doesn’t work in Safari 6.0 Developer Inspector, I can’t write any output in the console, which is frustrating.
No need to pass anything in. The function used for
addEventListenerwill automatically havethisbound to the current element. Simply usethisin your function:Here’s the fiddle: http://jsfiddle.net/dJ4Wm/
If you want to pass arbitrary data to the function, wrap it in your own anonymous function call:
Here’s the fiddle: http://jsfiddle.net/t4Gun/
If you want to set the value of
thismanually, you can use thecallmethod to call the function: