I tried to look for an answer before, however, I got stuck.
I'm trying to get multiple values out of the function. Values depend on some other parameters the user chooses. So, within the function from which I am trying to extract multiple values and use it later, each value goes through a test (if / else) and depending on the result/choosen options gets an accurate value.
Why am i getting undefined?
The concept would look like this:
function countries() {
var countrieslist;
var countriesIDs;
if ($("#1").is("checked") && !$("#2").is("checked")) {
var countrieslist = $("[for='1']").text();
} else if ($("#1").is("checked") && $("#2").is("checked")) {
var countrieslist = $("[for='1']").text() + " and " + $("[for='2']").text();
} else if (!$("#1").is("checked") && $("#2").is("checked")) {
var countrieslist = $("[for='2']").text();
}
if ($("#1").is("checked") && !$("#2").is("checked")) {
var countriesIDs = $("[for='1']").text();
} else if ($("#1").is("checked") && $("#2").is("checked")) {
var countriesIDs = $("[for='1']").text() + " and " + $("[for='1']").text();
} else if (!$("#1").is("checked") && $("#2").is("checked")) {
var countriesIDs = $("[for='2']").text();
}
/*
Works when i declare these variables manually:
var countrieslist = "countrieslist--- test";
var countriesIDs = "countriesIDs--- test";
*/
return {
countrieslist,
countriesIDs
}
}
cvalues = countries();
$("#1,#2").change(function() {
$(".countrieslist").text(cvalues.countrieslist)
$(".countriesIDs").text(cvalues.countriesIDs)
});
.row {
background: #f8f9fa;
margin-top: 5px;
}
.col {
padding: 10px;
}
<script src="https://code.jquery.com/jquery-3.4.1.slim.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<!--
Bootstrap docs: https://getbootstrap.com/docs
-->
<div class="container">
<div class="row">
<div class="col">
<div class="card text-dark mb-3" style="border-color: rgba(0, 0, 0, 0.125); background-color: rgb(255, 255, 255);">
<div class="card-header" style="border-color:none;background-color:rgba(0,0,0,.03)">Countries</div>
<div class="card-body ps-2 pe-2">
<input type="checkbox" class="btn-check" id="1" autocomplete="off">
<label class="btn btn-outline-secondary btn-sm mb-1" for="1">country1</label>
<input type="checkbox" class="btn-check" id="2" autocomplete="off">
<label class="btn btn-outline-secondary btn-sm mb-1" for="2">country2</label>
</div>
</div>
Countrieslist:
<div class="alert alert-success countrieslist" role="alert">
</div>
CountriesIDs:
<div class="alert alert-success countriesIDs" role="alert">
</div>
</div>
</div>
</div>
Same code on jsfiddle: https://jsfiddle.net/ribosed/a132okf5/44/
Thank you