How to use selected_gender variable outside the function
$('input[type=radio][name=pop_gender]').change(function() {
if (this.value == 'Male') {
var selected_gender = "gender_Male";
} else if (this.value == 'Female') {
var selected_gender = "gender_Female"
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="radio" name="pop_gender" id="gender_female" value="Female">
<input type="radio" name="pop_gender" id="gender_male" value="Male">
CodePudding user response:
1, Declare selected_gender variable before on change function called.
2, take value of clickd element in selected_gender variable
3, print that variable
Hope below code helps you to understand better.
let selected_gender = "";
$('input[type=radio][name=pop_gender]').on('change', function() {
selected_gender = this.value; //this will get value of input type is radio and name is pop_gender which was last time clicked
console.log(selected_gender); //in side of function
});
console.log(selected_gender); //out side of function
<html>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="radio" name="pop_gender" id="gender_female" value="Female">
<input type="radio" name="pop_gender" id="gender_male" value="Male">
</body>
</html>
CodePudding user response:
You could declare the var outside the function:
var selected_gender;
$('input[type=radio][name=pop_gender]').change(function() {
if (this.value == 'Male') {
selected_gender = "gender_Male";
} else if (this.value == 'Female') {
selected_gender = "gender_Female"
}
});
BUT instead check where you use it
let selected_gender = $('input[type=radio][name=pop_gender]:checked').val();
// here use "Male" or "Female"
On a DIFFERENT note:
How can I deal with diverse gender identities in user profiles?