I'm building a website using a website building and looking to toggle three text values on a click of a button. This is to toggle between USD and GBP values. I have the following code to toggle one piece of text but not clear how to add two other pieces of text for standard and premium fees?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p><button onclick="myFunction()">USD - GBP</button></p>
<div id="myDIV">Basic Fee $50</div>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.innerHTML === "Basic Fee $50") {
x.innerHTML = "Basic Fee £60";
} else {
x.innerHTML = "Basic Fee $50";
}
}
</script>
</body>
</html>
Hope someone is willing to help.
Assuming that you have no server-side logic to store the prices in and retrieve them dynamically, then the most simple and extensible way to achieve this would be to populate the DOM with all the currency values. You can show the default currency and hide the other one. Then on click of the button you can toggleClass()
to alternate as necessary.
jQuery($ => {
let $currencyValues = $('.currency-value');
$('.currency-toggle').on('click', () => {
$currencyValues.toggleClass('hidden');
});
});
/*
// the same in plain JS:
document.addEventListener('DOMContentLoaded', () => {
let currencyValues = document.querySelectorAll('.currency-value');
document.querySelector('.currency-toggle').addEventListener('click', () => {
currencyValues.forEach(el => el.classList.toggle('hidden'));
});
});
*/
.type {
display: inline-block;
min-width: 100px;
}
.currency-value.hidden { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<p><button class="currency-toggle">USD - GBP</button></p>
<div>
<span class="type">Basic Fee</span>
<span class="currency-value usd">$50</span>
<span class="currency-value gbp hidden">£60</span>
</div>
<div>
<span class="type">Handling Fee</span>
<span class="currency-value usd">$75</span>
<span class="currency-value gbp hidden">£100</span>
</div>
<div>
<span class="type">Another Fee</span>
<span class="currency-value usd">$100</span>
<span class="currency-value gbp hidden">£125</span>
</div>