Форма с полями обязательными к заполнению
by Misha Ivannikov
HTML
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/smoothness/jquery-ui.css">
<form name="formName" class="autoCheck" info="div#info">
<table>
<tr>
<th>Имя</th>
<td><input type="text" class="required" value="" alt="Имя" name="firstName" /></td></tr>
<tr>
<th>Фамилия</th>
<td><input type="text" class="required" value="" alt="Фамилия" name="secondName" /></td></tr>
<tr>
<th>Электронная почта</th>
<td><input type="text" class="required" value="" alt="Электронная почта" name="email" /></td></tr>
<tr>
<th>Телефон</th>
<td><input type="text" class="" value="" alt="Телефон" name="phone" /></td></tr>
<tr>
<td colspan="2"><input type="submit" name="" value="Submit" /></td></tr>
</table>
</form>
<div id="info"></div>
<!-- Second instance -->
<form name="formName2" class="autoCheck" info="div#info2">
<table>
<tr>
<th>Skype</th>
<td><input type="text" class="required" value="" alt="Skype" name="skype" /></td></tr>
<tr>
<th>icq</th>
<td><input type="text" class="required" value="" alt="ICQ" name="isq" /></td></tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td></tr>
</table>
</form>
<div id="info2"></div>
CSS
table, div {
margin: 5px;
border: none;
}
table th { width: 150px; }
input:focus { outline:none; }
input[type=text] {
margin: 2px;
border: 1px solid #999;
}
div {
width: 500px;
height: 50px;
pading: 5px;
}
.fail{ background-color: #FF9C9C; }
.ok{ background-color: #BDFFCA; }
div span.label {
background-color: #EEE;
border: 1px solid #CCC;
border-radius: 3px;
padding: 0 2px;
margin: 2px;
}
JavaScript
jQuery(function($) {
$.widget('ui.formChecker', {
options: {
classCheck: '',
classFail: '',
classOK: ''
},
_create: function() {
var self = this,
elem = $(self.element),
o = self.options;
elem.on('submit', function(e) {
if (self._check(elem) === false) {
elem.find('input.' + o.classFail + ':first').focus();
e.preventDefault();
self._trigger('onfail');
return false;
}
});
},
_check: function(elem) {
var o = this.options,
check = true;
$.each(elem.find('input.' + o.classCheck), function() {
if ($.trim(this.value) === '') {
check = false;
$(this).removeClass(o.classOK).addClass(o.classFail);
} else {
$(this).removeClass(o.classFail).addClass(o.classOK);
}
});
return check;
}
});
$('form.autoCheck').formChecker({
classCheck: 'required',
classOK: 'ok',
classFail: 'fail',
onfail : function(){
$($(this).attr('info')).html('Fail!!!');
}
});
});