32

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/

1
  • 2
    want this? You have to update fiddle settings change the 2nd dropdown to nowrap in <head> to fidddle! Commented Nov 3, 2014 at 7:57

5 Answers 5

23

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

your working example

Sign up to request clarification or add additional context in comments.

Comments

22

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>

Comments

16

using jQuery

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

jsFiddle

1 Comment

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.
5

You just try this, Its so easy

 <script>

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

</script>

2 Comments

How to get the text too
@Unbreakable : var e = document.getElementById("YourDropDownId"); var str = e.options[e.selectedIndex].value;
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

4 Comments

It doesn't solve the problem. Your answer just gives good advice.
Weird... It actually does. Sorry about that ;)
How to get the text also

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.