HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

jQuery Plugin for a Form

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
formpluginjqueryfor

Problem

jQuery plugin for a form. Looking for constructive criticism on my code. Thanks in advance!

```
// form.js
// splashinn

var Form = function(options) {

options = options || {};

this.url = options.url;
this.$fields = $(options.fields);
this.$status = $(options.status);
this.$submit = $(options.submit);
this.$form = options.form || 'form';
this.rFields = {
required: /[^.*]/,
nodigit: /^[^0-9]+$/,
email: /^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i,
};
this.required = [
this.rFields.nodigit,
this.rFields.email,
this.rFields.required,
this.rFields.required
];
this.errors = ['Please enter a valid name.', 'Please enter a valid email address.', 'You must enter a subject.', 'No message? But I wanted one :('];
}

Form.prototype.init = function init() {

this.$submit.click($.proxy(function(e) {
this.process(e);
}, this));

};

Form.prototype.process = function process(e) {

var filled = true;

e.stopImmediatePropagation();
e.preventDefault();

this.$fields.each($.proxy(function(i, element) {

var $element = $(element);

if (!$element.val().match(this.required[i])) {

$element.focus();
this.update(this.errors[i], true);
filled = false;
return false;
}
}, this));

filled && this.submit($(this.$form).serialize());
};

Form.prototype.update = function update(message, isError) {

if (isError && this.$status.hasClass('error')) {

this.$status.addClass('error')
.text(message);

setTimeout($.proxy(function() {
this.$status.removeClass('shake');
}, this), 500);
} else {
this.$status.fadeOut();

setTimeout($.proxy(function() {
this.$status.text(message)
.fadeIn();

if (isError) {
this.$status.removeClass('shake')
.addClass('error'

Solution

It's not necessary to name your methods as below. Someone may reference to it further.

Form.prototype.submit = function submit(data) {
...
}


You can just simply define it as follows

Form.prototype.submit = function (data) {
...
}


ES6 style ;)

Form.prototype.submit = (data) => {
...
}


Form.prototype.init looks as moot method. This is exact what constructor has to do.

I take into account that you are developing a plugin so you're going to reuse it. Right? Thus your CSS classes such as "error", "info", etc. have to be configurable as well as other stuff. Or at least add unique prefix to it.

Code Snippets

Form.prototype.submit = function submit(data) {
...
}
Form.prototype.submit = function (data) {
...
}
Form.prototype.submit = (data) => {
...
}

Context

StackExchange Code Review Q#139541, answer score: 2

Revisions (0)

No revisions yet.