I mean…
You’ve put an enable trigger for the click function… inside… the click function.
$('#srcsubmit').on('click', function () {
//$('#srcsubmit').on("click");
$('.srchBoxError').html('Just a click test');
});
});
The only way that commented line ever gets called is if the function is currently attached. So we… don’t need to attach it again there, surely. (Note: On/Off is not a disable/enable switch, it’s a New Bind / Remove Bind. If you bind multiple ‘on clicks’ to an element, it will fire ALL of them when the element is clicked.)
So, lets make things a little easier on ourselves. Let us define our function separately.
function clickableButton() {
$('.srchBoxError').html('Just a click test');
}
Why? So we have a name to use later.
Now. We want the function to be bound to the button on load.
$(function () {
$('#srcsubmit').on('click', clickableButton);
simple enough. Now, if we change the dept selectbox, we want to disable the click. And the button, while we’re at it. (Note: I’m still inside the same $(function() { from before)
$('#dept').on('change', function () {
depts = $('#dept option:selected').html();
$("#srcsubmit").off("click");
$("#srcsubmit").addClass('disable');
$('.srchBoxError').html(' ');
});
Simple enough again. We could have said $("#srcsubmit").off("click",clickableButton);
, if there were other click events on the button that we didnt want to touch. We’ll see that in a second.
Now, we want to ENABLE the button if the reset button is clicked. But there’s a problem. We don’t know if the event is already active when someone clicks that button. If we bind another .on to it, we might be binding a second click event. So we need to be a little more sneaky. How do we guarantee that there is only one instance of our click event on the button?
For an example, I’m going to use oranges. When i invoke .on
, I give you an orange. If i do it twice, I give you two oranges. I dont want that. But, when I invoke .off()
, I take away all oranges, regardless of the number of oranges.
So, how do I guarantee that you only have 1 orange when i’m done, using only these two operations, and not knowing how many oranges you currently have? First, I take away your oranges. Then i give you one.
$('#bdReset').on('click', function() {
$("#srcsubmit").off("click",clickableButton).on("click",clickableButton);
$("#srcsubmit").removeClass('disable');
$('.srchBoxError').html(' ');
});
});
(The extra });
is me finally closing that onload call from the first block of code)