I have a web page with Stripe Elements on it. Everything works. But I want to show a spinner after the Pay button is clicked, but only if all the credit card fields are complete and validated. The problem is that Stripe's client-side API/structure prevents me from examining those fields with javascript. I can tap into the button click easy enough by doing this:
$("#btnPay").click(function() {
// show spinner
});
But I don't ever want to show the spinner unless all credit card fields are filled out and complete. Otherwise the spinner would pop up when there are fields still empty, etc.
Is there a way in Stripe Elements API to inject my js that launches the spinner AFTER the form has been validated by Stripe, but BEFORE it makes the ajax call to get the token?
Here are some portions of my page:
Some js:
<script>
function setOutcome(result) {
var successElement = document.querySelector('.success');
var errorElement = document.querySelector('.error');
successElement.classList.remove('visible');
errorElement.classList.remove('visible');
if (result.token) {
// my ajax here
} else if (result.error) {
errorElement.textContent = result.error.message;
errorElement.classList.add('visible');
}
}
</script>
HTML form:
<form action="//httpbin.org/post" method="POST">
<input type="hidden" name="token" />
<div class="group">
<label>
<span>Credit Card</span>
<div id="card-element" class="field"></div>
</label>
</div>
<div class="group">
<label>
<span>Name on Card</span>
<input id="name" name="name" class="field" placeholder="Your name here" />
</label>
</div>
<button type="submit" id="btnPay" style="cursor: pointer; width: 200px; margin-left: 155px;">Pay $115.00</button>
</form>
Some more js:
<script>
var stripe = Stripe('pk_test_3Z8D***********C');
var elements = stripe.elements();
var card = elements.create('card', {
hidePostalCode: true,
style: {
base: {
iconColor: '#666EE8',
color: '#31325F',
lineHeight: '40px',
fontWeight: 300,
fontFamily: 'Helvetica Neue',
fontSize: '15px',
'::placeholder': {
color: '#CFD7E0',
},
},
}
});
card.mount('#card-element');
card.on('change', function (event) {
setOutcome(event);
});
document.querySelector('form').addEventListener('submit', function (e) {
e.preventDefault();
var options = {
name: document.getElementById('name').value,
};
stripe.createToken(card, options).then(setOutcome);
});
</script>
Any ideas?
result.token
is the answer, as explained by Paul. – HerrimanCoder