I developed a JS script to calculate the price based on its weight, however I cannot change the country in the calculation, it remains on the default one.
I use a json file to retrieve the prices, weights, countries.
<select name="country" id="country" class="form-control">
<option value="BE">Belgique</option>
<option value="FR">France</option>
</select>
My js script
window.addEventListener('load', () => {
let country = document.getElementById('country').value;
document.getElementById('country').addEventListener('change', function() {
let country = this.value;
});
function getShippingPrice(weight) {
// Sort the shippingPrices array by weight in descending order
shippingPrices.sort((a, b) => b.weight - a.weight);
//console.log(shippingPrices);
let closestLowerWeight = null;
for (let i = 0; i < shippingPrices.length; i++) {
if (shippingPrices[i].country === country) {
if (shippingPrices[i].weight <= weight) {
closestLowerWeight = shippingPrices[i];
break; // Stop searching when we find a weight less than or equal to the target weight
}
}
}
if (closestLowerWeight) {
return closestLowerWeight.price; //+ ' €';
}
// If no match is found, you can handle this case, e.g., return a default price
return "Price not found for this weight";
}
});
Data
var shippingPrices = [{"country":"BE","price":10,"weight":0.11},{"country":"BE","price":20,"weight":10},{"country":"BE","price":30,"weight":30},{"country":"BE","price":50,"weight":50},{"country":"BE","price":85,"weight":100},{"country":"FR","price":5,"weight":0.11}];
If I change country no calculation it does not change country
Best Regards