I want to display alert when someone chose both options from the html select option element what they have chosen. but my function are not working properly in my exchange function there the alert i am getting is "you want to change From undefined To undefined ". The variable I set on the exchange function from and to is getting replace by undefined. But I don't understand why this is happening i have declared them already.
$( ".my_Class1" ).each(function( index ) {
$( this ).on("change",choice_1)
});
function choice_1(){
var from = this.value;
return from;
}
$( ".my_Class2" ).each(function( index ) {
$( this ).on("change",choice_2)
});
function choice_2(){
var to = this.value;
return to;
}
function exchange() {
var first = choice_1();
var second = choice_2();
if(first === second){
alert("you want to change From " + first + " To " + second); //in alert in the browser " You want to change from undefined to undefined"
}else{
alert("you want to change From " + first + " To " + second); // Here Also getting the same
}
}
$( ".my_Class1, my_Class2" ).each(function( index ) {
$( this ).on("change", exchange)
});
The problem is when you call var first = choice_1(); in your exchange() function, the choice_1() function refers to this which has no real context when you call it from within exchange().
When you call it from the on change event, it makes sense. The this context is the selected option.
So one possible solution is to call exchange() from within your choice_1() and choice_2() functions where from and to can be passed on with the correct context.
Here's a partial refactoring of your code which should show the options you selected in the alert. Be aware that no option is preselected on page load, so the first time you select an option the other value will be undefined.
var from, to;
function choice_1() {
from = this.value;
exchange(from, to)
}
function choice_2() {
to = this.value;
exchange(from, to)
}
function exchange(from, to) {
alert("you want to change From " + from + " To " + to);
}
$(".my_Class1").each(function(index) {
$(this).on("change", choice_1)
});
$(".my_Class2").each(function(index) {
$(this).on("change", choice_2)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>From</label>
<select class="my_Class1">
<option>Select</option>
<option value="a">A</option>
<option value="b">B</option>
</select>
<br><br>
<label>To</label>
<select class="my_Class2">
<option>Select</option>
<option value="a">A</option>
<option value="b">B</option>
</select>