Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: Call function by name on select change

I'm trying to call a function by name .onchange of a select but nothing happens. When the function is describled after the attribute, it works.

THIS DOESN'T WORK

HTML:

<select id="numb">
  <option value="1">1</option>
  <option value="2">2</option>
</select>

SCRIPT:

<script type="text/javascript">
    $('#numb').change(testMessage);
</script>

<script type="text/javascript">
    function testMessage(){
        alert('Hello');
    }
</script>

THIS WORKS

HTML:

<select id="numb">
  <option value="1">1</option>
  <option value="2">2</option>
</select>

SCRIPT:

<script type="text/javascript">
    $('#numb').change(function(){
      alert('Hello')
    });
</script>

EDIT:

Ok, for all those who said me to include the function on the same script. This is not possible because the testMessage() function is in an external .js script included on the <head> of the HTML.

like image 442
Perocat Avatar asked Aug 14 '13 18:08

Perocat


People also ask

How to call function from div?

You can name each function according to the div 's id and call it dynamically using the object["methodName"]() syntax to call it.

How do I get the select box value?

Answer: Use the jQuery :selected Selector You can use the jQuery :selected selector in combination with the val() method to find the selected option value in a select box or dropdown list.


2 Answers

It is because the handler testMessage is not defined when binding it to the change event.

It should work if it was in the same script context like below,

<script type="text/javascript">
    $('#numb').change(testMessage);

    function testMessage(){
        alert('Hello');
    }
</script>

Code inside <script></script> are executed one by one progressive from top and testMessage function doesn't exist inside the first <script></script>.

You have couple of options here,

  1. Put it inside an anonymous function which will let your script to resolve the testMessage function later. [As suggested in Optimus Prime answer]

    <script type="text/javascript">
      $('#numb').change(function () { 
         testMessage
      });
    </script>
    <script type="text/javascript">
       function testMessage(){
          alert('Hello');
       }
    </script>
    
  2. Include the script that has testMessage function above the script that binds the testMessage like below,

    <script type="text/javascript">
    function testMessage(){
        alert('Hello');
    }
    </script>
    <script type="text/javascript">
      $('#numb').change(testMessage);
    </script>
    
like image 164
Selvakumar Arumugam Avatar answered Oct 03 '22 22:10

Selvakumar Arumugam


Instead try ,

<script type="text/javascript">
    $('#numb').change(function(){
       testMessage();
    });
</script>
like image 37
Optimus Prime Avatar answered Oct 03 '22 20:10

Optimus Prime