Semantic UI form validation scroll to first error
Semantic UI form validation scroll to first error
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.1.8/semantic.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.1.8/semantic.min.js"></script>
<form class="ui form validation-form" method="post">
<div class="field">
<label>Empty</label>
<input name="empty" id="empty" type="text">
</div>
<div class="field">
<label>Select</label>
<select name="select" id="select" class="ui dropdown">
<option>Select</option>
<option value="male">male</option>
<option value="female">female</option>
</select>
</div>
<div class="field">
<label>Empty1</label>
<input name="empty2" id="empty2" type="text">
</div>
<div class="field">
<label>Empty2</label>
<input name="empty2" id="empty3" type="text">
</div>
<div class="field">
<label>Empty3</label>
<input name="empty2" id="empty4" type="text">
</div>
<div class="field">
<label>Empty</label>
<input name="empty5" id="empty5" type="text">
</div>
<div class="field">
<label>Empty</label>
<input name="empty6" id="empty6" type="text">
</div>
<div class="field">
<label>Empty</label>
<input name="empty7" id="empty7" type="text">
</div>
<div class="field">
<label>Dropdown</label>
<select class="ui dropdown" name="choice" id="choice">
<option value="">Select</option>
<option value="male">Choice 1</option>
<option value="female">Choice 2</option>
</select>
</div>
<div class="inline field">
<div class="ui checkbox">
<input name="checkbox" id="checkbox" type="checkbox">
<label>Checkbox</label>
</div>
</div>
<div class="ui submit button">Submit</div>
<div class="ui error message"></div>
</form>
JavaScript
$('.validation-form')
.form({
on: 'blur',
onFailure: function(formErrors, fields) {
$.each(fields, function(e) {
var ele = $('#' + e);
var fail = (ele.val() === false || ele.val().length === 0);
if (fail) {
console.log(ele, fail);
ele.focus();
$('html,body').animate({
scrollTop: ele.offset().top - ($(window).height() - ele.outerHeight(true)) / 2
}, 200);
return false;
}
});
return false;
},
fields: {
empty: {
identifier: 'empty',
rules: [{
type: 'empty',
prompt: 'Please enter a value'
}]
},
empty2: {
identifier: 'empty2',
rules: [{
type: 'integer',
prompt: 'Please enter a value'
}]
},
select: {
identifier: 'select',
rules: [{
type: 'empty',
prompt: 'Please enter a value'
}]
},
empty3: {
identifier: 'empty3',
rules: [{
type: 'empty',
prompt: 'Please enter a value'
}]
},
empty4: {
identifier: 'empty4',
rules: [{
type: 'empty',
prompt: 'Please enter a value'
}]
},
empty5: {
identifier: 'empty5',
rules: [{
type: 'empty',
prompt: 'Please enter a value'
}]
},
empty6: {
identifier: 'empty6',
rules: [{
type: 'empty',
prompt: 'Please enter a value'
}]
},
empty7: {
identifier: 'empty7',
rules: [{
type: 'empty',
prompt: 'Please enter a value'
}]
},
dropdown: {
identifier: 'choice',
rules: [{
type: 'empty',
prompt: 'Please select a dropdown value'
}]
},
checkbox: {
...