Update prices using JS and JSON with a simple HTML form
P粉294954447
2023-08-18 12:38:26
<p>I'm trying to create a setup where you enter a zip code, submit the form, and then use JavaScript to check if the first 4 characters of the zip code match the zip code in some JSON data, and if so , then change the price on the page. This will be for a Shopify site, so any help on how to implement it there would be great. </p>
<p>Currently when I submit the form the page refreshes but nothing happens. </p>
<p>Here’s what I have so far, still in the early stages: </p>
<p><br /></p>
<pre class="brush:js;toolbar:false;">async function checkZones() {
// const requestURL = "{{ 'zones.json' | asset_url }}";
// const request = new Request(requestURL);
//const response = await fetch(request);
// const zones = await response.json();
const zones = [{
"name": "zone 1",
"postcodes": [
"test1",
"test2",
"test3",
"test4",
"test5",
"test6",
"test7",
"test8",
"test9",
"test10"
],
"cost": 10.8
},
{
"name": "zone 2",
"postcodes": [
"test12",
"test13",
"test14",
"test15",
"test16",
"test17",
"test18",
"test19",
"test18",
"test19",
"test20"
],
"cost": 16.8
}
]
console.log(zones);
updatePrice()
}
function updatePrice(zone) {
const postcodeFormInput = document.querySelector('#postcodeForm input[type="text]"');
const postcodes = zone.postcodes;
for (const code of postcodes) {
if (postcodeFormInput.value.contains(code)) {
const productPrice = document.querySelector('#ProductPrice-product-template').textContent;
if (code === "test1") {
const newPrice = productPrice zone.cost;
document.querySelector('#ProductPrice-product-template').innerHTML = newPrice;
}
}
}
}</pre>
<pre class="brush:html;toolbar:false;"><form onsubmit="checkZones()" id="postcodeForm">
<input type="text">
<button type="submit">Update Costs</button>
</form><span id="ProductPrice-product-template">0.00</span></pre>
<p><br /></p>
Some questions here
Some of the questions:
?.
to handle missing postal codes