Created
August 14, 2019 14:02
-
-
Save mdunbavan/e8754b3ab10ed2f0872b2bec4f89af2d to your computer and use it in GitHub Desktop.
postcode form js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% includejs %} | |
$('.postcode-form').submit(function(ev) { | |
// Prevent the form from actually submitting | |
ev.preventDefault(); | |
var inputVal = $(this).find('input').val(); | |
if(inputVal.length == 0 ){ | |
$(this).find('input').addClass('b--red'); | |
$('.error').show(); | |
$('.error').html('Please make sure you enter a valid postcode'); | |
} else { | |
var data = {}; | |
data[window.csrfTokenName] = window.csrfTokenValue; | |
data['action'] = 'postman/rates/estimate'; | |
data['variantId'] = {{ variants[0].id }}; | |
data['address']['zipCode'] = inputVal; | |
data['address']['countryCode'] = 'GB' | |
console.log(data) | |
// Send it to the server | |
$.post( | |
window.location.href, data | |
).done(function(response){ | |
if (response.success) { | |
console.log(response) | |
var results = response.rates; | |
var rateAmounts = []; | |
var t = results.map(function (rate) { | |
if (rate.serviceName == "Collect from Showroom") { | |
$('.is-collection').removeClass('dn'); | |
return rate; | |
} else if(rate.serviceHandle == "free_shipping"){ | |
$('.delivery-text').html(rate.serviceName); | |
$('.is-collection').removeClass('dn'); | |
return rate; | |
} else { | |
var resultRate = rate.amount; | |
rateAmounts.push(resultRate); | |
} | |
}); | |
const minRate = Math.min.apply(null, rateAmounts); | |
$('.delivery-text').removeClass('dn'); | |
$('.cheapest-delivery').html('£'+minRate); | |
} else { | |
alert('error'); | |
} | |
}) | |
.fail(function(jqXHR, textStatus, errorThrown){ | |
$('.error').show(); | |
$('.error').html('Ooops theres an error, please check postcode is valid'); | |
}) | |
} | |
}); | |
{% endincludejs %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment