Two function have an onchange event based on single dropdown but that
onchange event has different condition on each function, when I call
function fun1 it triggers onchange what I mentioned in fun1, but when I
call fun2 it triggers both onchange. How to restrict it?
HTML
<select id='number'>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
jquery
function fun1() {
$('#number').on('change', function() {
var val = this.value;
if(val > 2){
console.log('hello first function');
}
});
}
function fun2() {
$('#number').on('change', function() {
var val = this.value;
if(val < 2){
console.log('hello second function');
}
});
}
When I called fun1 my output = 'hello first function'. When I called fun2 my output = 'hello second function'. When I again call my fun1 my output = 'hello first function' 'hello second function', but I need my output like this='hello first function'.
CodePudding user response:
I think you could do it this way, by overriding a function variable:
// default function, do nothing
let delegate = () => {};
// assign the delegate to fun1's onchange content
function fun1() {
delegate = () => {
var val = this.value;
if(val > 2){
console.log('hello first function');
}
}
}
// assign the delegate to fun2's onchange content
function fun2() {
delegate = () => {
var val = this.value;
if(val < 2){
console.log('hello second function');
}
}
}
$('#number').on('change', function() {
delegate();
});
CodePudding user response:
The reason why it is not working is: The $('#number').on('change', function() {...}) is itself a function, it doesn't need to get wrapped inside a function that is getting executed only once... And hence it is not working properly...
By the way you can do this in very short way without needing extra functions :
$("#number").on("change", function() {
let val = this.value
if(val > 2){
console.log("hello first function")
//you can execute your first function here
//or you can whatever your first function does here
}
else{
console.log('hello second function');
//same goes here
}
})
This is very optimized way to do what you want...
