Skip to content

Instantly share code, notes, and snippets.

@chrishutchinson
Last active November 23, 2017 18:04
Show Gist options
  • Save chrishutchinson/573e0307698734e5e3ba892f6a279112 to your computer and use it in GitHub Desktop.
Save chrishutchinson/573e0307698734e5e3ba892f6a279112 to your computer and use it in GitHub Desktop.
// Polymer template code
<form autocomplete="off" id="form" on-submit="handleFormSubmit">
<input type="text" name="income" placeholder="Enter your annual income (£)" />
<div class="selectWrapper">
<i class="Icon Icon--arrowDown"></i>
<select name="category" id="dropdown">
<option value="" disabled selected>Your status</option>
</select>
</div>
<input type="submit" value="Search" class="Button" />
</form>
<template is="dom-if" if={{error}}>
<div class="error">{{error}}</div>
</template>
// Polymer JavaScript code
const cleanIncome = income => parseInt(income.replace(/([^\d.]+)/g, ''));
const validateIncome = income => {
// Was an income provided?
if(income === '' || !income)
return {
isValid: false,
error: 'There has been a problem parsing your income.'
};
// Is the income too small?
if(income < 10000)
return {
isValid: false,
error: 'Please input an income greater than £10,000.'
};
// Provided income is valid!
return {
isValid: true,
error: null
};
};
handleFormSubmit: function(event) {
event.preventDefault();
// 0. Get input data
const form = event.target;
const income = form.income.value;
const dropdownSelection = form.category.value;
// 1. Reset error state
this.error = null;
// 2. Clean input data
const cleanedIncome = cleanIncome(income);
// 3. Validate input data
const { isValid, error } = validateIncome(cleanIncome);
if(!isValid) {
// 4. Show error
this.error = error;
return;
}
// 5. Show results and send analytics event
this.showData({
income: cleanedIncome,
case: dropdownSelection,
});
ga('send', 'event', 'budget-calculator', 'income', cleanedIncome);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment