22

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/

Shaggy
  • 4,043
  • 22
  • 84
  • 144

5 Answers5

20

Your code is working just fine, you have to declare javscript method before DOM ready.

your working example

SilentTremor
  • 4,279
  • 2
  • 14
  • 26
14

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:

<script type="text/javascript">
function jsFunction(value)
{
    alert(value);
}
</script>

<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>
Bartek Andrzejczak
  • 1,152
  • 2
  • 11
  • 25
8

using jQuery

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

jsFiddle

Alex
  • 6,714
  • 26
  • 84
  • 140
  • What if I want to get the text of the selection too. I tried `$(this).text()` but it shows all the texts for all the dropdown for every single click. – Unbreakable Jul 28 '17 at 13:32
4

You just try this, Its so easy

 <script>

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

</script>
jeet.chanchawat
  • 5,228
  • 5
  • 31
  • 57
Dinesh.net
  • 69
  • 1
  • 9
1

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

bemol
  • 258
  • 3
  • 15