Skip to content

Instantly share code, notes, and snippets.

@KerryRitter
Last active April 12, 2017 17:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KerryRitter/d648993e6357282fdc93c0a4894f1281 to your computer and use it in GitHub Desktop.
Save KerryRitter/d648993e6357282fdc93c0a4894f1281 to your computer and use it in GitHub Desktop.
jQuery TS example
class MembershipPaymentForm {
private get form() {
return $("#membership-payment-form");
}
private get individualElements() {
return this.form.find("*[type='individual']");
}
private get partnerElements() {
return this.form.find("*[type='partner']");
}
private get planTypeRadio() {
return this.form.find("input[name='plan-type']");
}
private get planTypeDropdowns() {
return this.form.find(".plan-type-dropdown");
}
private get selectedPlanTypeDropdown() {
return this.form.find(".plan-type-dropdown:visible");
}
private get planTypeNameDisplay() {
return this.form.find("#plan-type-name-display");
}
private get planTypeValueDisplay() {
return this.form.find("#plan-type-value-display");
}
private get selectedPlanTypeName() {
let selectedPlanTypeName = this.selectedPlanTypeDropdown.find("option:selected").text();
return selectedPlanTypeName.split("—")[0].trim();
}
private get selectedPlanTypeValue(): number {
return parseInt(this.selectedPlanTypeDropdown.val());
}
public constructor() {
if (this.form.length === 0) {
return;
}
this.planTypeRadio.on("change", e => this.handlePlanTypeChange($(e.target)));
this.planTypeDropdowns.on("change", e => this.handlePlanTypeChange(this.planTypeRadio));
this.form.on("submit", e => this.handleFormSubmit(e));
this.planTypeRadio.eq(0).click();
}
/// planTypeRadio must be passed because on radio change, we need the event target.
private handlePlanTypeChange(planTypeRadio: JQuery) {
if (planTypeRadio.val() === "individual") {
this.individualElements.show();
this.partnerElements.hide();
} else {
this.individualElements.hide();
this.partnerElements.show();
}
this.planTypeNameDisplay.text(this.selectedPlanTypeName);
this.planTypeValueDisplay.text(this.selectedPlanTypeValue);
}
private handleFormSubmit(e: JQueryEventObject) {
e.preventDefault();
e.stopPropagation();
const endpoint = this.form.attr("action");
jQuery.ajax({
url: endpoint,
type: "POST",
dataType: "json",
data: this.form.serialize()
}).then(response => {
console.log(response);
}).fail(response => {
const errorMessage = response.responseJSON;
console.log(errorMessage);
});
return false;
}
private fillInput(id: string, value: string) {
this.form.eq(0).find(`#${id}`).val(value);
}
}
export default new MembershipPaymentForm();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment