I'm trying to add an onChange event handler to two element of my html page. Sadly the event is firing when the page loads which is causing downstream issues.
$("#Division").on('click', onChangeFilter());
$("#Program").change(onChangeFilter());
function onChangeFilter() {
alert("Fired to soon....");
};
The associated HTML for testing looks like this
<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>
Is adding the .change event causing a 'change' and triggering the function? The two closest posts I was able to find are located here and here but I feel their issues were more transparent. Nothing was obvious to me in the jQuery API indicating this behavior. I just started transitioning to the web world in my course work, maybe I'm not understanding correctly the dynamics of how a page loads the DOM. I thought this page useful but not sure how accurate. Thank you in advance for the guidance.
You'll want to remove the invoking parenthesis after each use of onChangeFilter
:
$("#Division").on('click', onChangeFilter);
// ^^
$("#Program").change(onChangeFilter);
// ^^
This treats the function as any other (object) value, passing it as an argument to .on()
and .change()
for them to use and for the events to invoke when they've been triggered.
Otherwise, with the parenthesis, the function is being called first and its return
value is instead passed to .on()
and .change()
, similar to:
var result1 = onChangeFilter();
$("#Division").on('click', result1);
var result2 = onChangeFilter();
$("#Program").change(result2);
When you write like this:
$("#Division").on('click', onChangeFilter());
you are calling it. The () after method name means you are calling it. Just write the method name there.
The code more-less should be like this:
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With