30

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
  • 5,422
  • 28
  • 98
  • 163
  • 2
    [want this](http://jsfiddle.net/6uyz4b8x/2/)? You have to update fiddle settings change the 2nd dropdown to **nowrap in ** to fidddle! – Dhaval Marthak Nov 03 '14 at 07:57

5 Answers5

22

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

your working example

SilentTremor
  • 4,747
  • 2
  • 21
  • 34
20

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,292
  • 2
  • 14
  • 27
15

using jQuery

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

jsFiddle

Alex
  • 8,908
  • 28
  • 103
  • 157
  • 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
5

You just try this, Its so easy

 <script>

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

</script>
jeet.chanchawat
  • 5,842
  • 5
  • 38
  • 59
Dinesh.net
  • 79
  • 1
  • 9
2

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
  • 381
  • 3
  • 18