[javascript] call javascript function onchange event of dropdown list

I want to invoke javascript function when value in the dropdown list changes. I dont want to hardcode dropdown list id .

Hence not using document.getElementById

My Code:

<select id ="ddl" name="ddl" onmousedown="this.value='';" onchange="jsFunction(this.value);">
  <option value='1'>One</option>
  <option value='2'>Two</option>
  <option value='3'>Three</option>
</select>

function jsFunction(value)
{
    alert(value);
}

This is giving error ReferenceError: jsFunction is not defined

Fiddle : http://jsfiddle.net/6uyz4b8x/1/

This question is related to javascript html

The answer is


jsFunction is not in good closure. change to:

jsFunction = function(value)
{
    alert(value);
}

and don't use global variables and functions, change it into module


You just try this, Its so easy

 <script>

  $("#YourDropDownId").change(function () {
            alert($("#YourDropDownId").val());
        });

</script>

I don't know why do you need this onmousedown event here, but what you have to do is put your function above actual usage. Look at the snipplet below:

_x000D_
_x000D_
<script type="text/javascript">_x000D_
function jsFunction(value)_x000D_
{_x000D_
    alert(value);_x000D_
}_x000D_
</script>_x000D_
_x000D_
<select id ="ddl" name="ddl" onmousedown="this.value='';" onchange="jsFunction(this.value);">_x000D_
  <option value='1'>One</option>_x000D_
  <option value='2'>Two</option>_x000D_
  <option value='3'>Three</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_


using jQuery

 $("#ddl").change(function () {
                alert($(this).val());
            });

jsFiddle