I'm a JavaScript total beginner and I've gotten stuck on something that seems like it should work while trying to set a variable with a an if/else condition inside and anonymous function. Here is my code:
function changeValue(){
var newValue = (function(){
var getRadioValue = $( "input:radio[name=Radio1]:checked" ).val();
if (getRadioValue === 5){
var final = 8;
}
else if (getRadioValue === 4){
var final = 5;
}
else if (getRadioValue === 3){
var final = 3;
}
else if (getRadioValue === 2){
var final = 1;
}
else if (getRadioValue === 1){
var final = -1;
}
else
{
var final = 0;
}
return final;
})();
alert(newValue);
}
Right now, the alert is showing 0 because none of the "ifs" are returning true, but if I set the getRadioValue variable hard coded like:
var getRadioValue = 5;
then the if/else conditional works and the alert message shows 8. That makes it seem like the .val() method isn't working. However, if I simply set the alert to:
alert(getRadioValue);
The alert message does in fact display the correctly selected radio value from the radio button set on my page. So I know that is working... Now I can't figure out where I'm going wrong. It seems like since the radio value is getting assigned to getRadioValue correctly, and the conditional is working, the whole thing should work. I'm sure it's such a basic problem, but after much research I still can't seem to get it. Any help is greatly appreciated!