Trying to prevent Javascript from starting on page load

I am trying to add an onChange event handler to two elements of my html page. Unfortunately, the event fires when a page loads, which causes problems after exiting.

$("#Division").on('click', onChangeFilter());
$("#Program").change(onChangeFilter());

function onChangeFilter() {
   alert("Fired to soon....");
};

The relevant HTML for testing is as follows:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
</head>
<body>
   <div id="DivisionSelection">
     <select id="Division" data-filterprogramcontrol="Program">
       <option value="-1">Select Division</option>
       <option value="1">Item 1</option>
       <option value="2">Item 2</option>
       <option value="3">Item 3</option>
     </select>
  </div>    
</body>
</html>

.change, "" ? , , , , , jQuery API, . - , , , DOM. , , , . .

+4
2

onChangeFilter:

$("#Division").on('click', onChangeFilter);
//                                      ^^
$("#Program").change(onChangeFilter);
//                                ^^

() , .on() .change() , .

, return .on() .change(), :

var result1 = onChangeFilter();
$("#Division").on('click', result1);

var result2 = onChangeFilter();
$("#Program").change(result2);
+7

:

$("#Division").on('click', onChangeFilter());

. , . .

- :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<script>
    $(document).ready(function() {
        var onChangeFilter = function(evt){
           alert("Fired to soon....");
        };
        $("#Division").on('click', onChangeFilter);
        $("#Program").on('change', onChangeFilter);

    });
</script>
</head>
<body>
   <div id="Division">
     <select id="Program">
       <option value="-1">Select Division</option>
       <option value="1">Item 1</option>
       <option value="2">Item 2</option>
       <option value="3">Item 3</option>
     </select>
  </div>    
</body>
</html>
+1

All Articles