I have seed Country with name, number_code and iso. For Currency I have used money-rails gem. When I select Country I want user to autoselect its correspoinding currency. When I select USA auto selct USD and if user wants to chnage currency they can change it as well.
I have done this with ajax.
I have method in controller get_currency I got response {"currency":{"name":"Aruban Florin","symbol":"ƒ","iso_code":"AWG"}}
.
// country, currency select dropdown start
var countryDropdown = $('#country-select');
var currencyDropdown = $('#currency-select');
// Handle country dropdown change and set initial state of currency dropdown
function updateCurrencyDropdown(countryId) {
$.ajax({
url: '/company_countries/get_currency',
type: 'GET',
data: { country_id: countryId },
success: function(response) {
var currency = response.currency;
var currencyOption;
var selectedCurrency = currencyDropdown.val();
if (currency && currency.name) {
console.log(currency)
currencyOption = `<option value="${currency.iso_code}">${currency.name} (${currency.symbol})</option>`;
console.log(currencyOption)
currencyDropdown.find(`option[value="${currency.iso_code}"]`).remove(); // remove currency option from the dropdown
currencyDropdown.prepend(currencyOption); // Add new currency option at the top
if (selectedCurrency !== currency.iso_code) {
currencyDropdown.val(currency.iso_code);
console.log("currencyDropdown", currencyDropdown)
}
} else {
currencyOption = '<option value="USD">US Dollar (USD)</option>';
currencyDropdown.empty().append(currencyOption); // Clear previous options and add default option
}
}
});
}
// Set initial state of currency dropdown based on initial value of country dropdown
var initialCountryId = countryDropdown.val();
updateCurrencyDropdown(initialCountryId);
// Handle country dropdown change
countryDropdown.on('change', function() {
var countryId = $(this).val();
updateCurrencyDropdown(countryId);
});
// country, currency select dropdown end
I got only 1 or 2 optins here. If I select Austria get Euro and USD. What about list of other currency as an option.