Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call javascript function onchange event of dropdown list

Tags:

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/

like image 451
Shaggy Avatar asked Nov 03 '14 07:11

Shaggy


People also ask

How do you attach a single Onchange event with multiple dropdowns?

Best procedure for cases like this would be, to add a common class to all the dropdowns for which you want to call the function on change. For ex: add 'trigger-change' class for all your required dropdowns. Then below bind event should work perfect for you. $('form select.

How does Onchange event work in JavaScript?

The onchange event occurs when the value of an element has been changed. For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed.

Which event is called on selection of an item from a dropdown list?

The HTML Select DropDownList has been assigned a jQuery OnChange event handler. When an item is selected in the HTML Select DropDownList, the jQuery OnChange event handler is executed within which the Text and Value of the selected item is fetched and displayed in JavaScript alert message box.


3 Answers

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

your working example

like image 51
SilentTremor Avatar answered Oct 08 '22 18:10

SilentTremor


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>
like image 40
Bartek Andrzejczak Avatar answered Oct 08 '22 19:10

Bartek Andrzejczak


using jQuery

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

jsFiddle

like image 42
Alex Avatar answered Oct 08 '22 19:10

Alex