JSFiddle - React, Tailwind, and code Playground
by Minko Gechev
HTML
<button id="saveFormButton">Запиши</button><br />
<button class="add-student-button" class="btn">Добави студент</button>
<div class="student">
Студент: <input type="text" class="student-name" /><br />
Дисциплини:
<div class="disciplines-list">
<input type="text" class="discipline" />
</div>
<div>
<button class="add-discipline-button" class="btn">Добави дициплина</button>
</div>
</div>
CSS
.add-discipline-button {
}
.error {
border: 2px solid red;
}
input {
border: 1px solid black;
outline: none;
}
JavaScript
var MAX_DISCIPLINES_COUNT = 7,
MAX_STUDENTS_COUNT = 3;
$(document).on('click', '.add-discipline-button', function () {
var container = $(this).parent().prev();
if (container.children('input').length > MAX_DISCIPLINES_COUNT) {
return;
}
container.prepend('<input type="text" class="discipline" />');
});
$(document).on('click', '.add-student-button', function () {
var container = $(document.body),
proto = $('.student').first();
if (container.children('.student').length > MAX_STUDENTS_COUNT) {
return;
}
var studentForm = proto.clone();
container.append(studentForm);
studentForm.fadeOut(0);
studentForm.fadeIn(300);
});
$(document).on('click', '#saveFormButton', function () {
var students = [];
if (validateForm()) {
$('.student').each(function (index, elem) {
var name = $(elem).children('.student-name').val(),
disciplines = [];
$(elem).find('.discipline').each(function (index, elem) {
disciplines.push($(elem).val());
});
students.push({
name: name,
disciplines: disciplines
});
});
}
});
var validDisciplines = [
'ASP.NET',
'APIS',
'Python'
];
function validateForm() {
$('.student-name').each(function (index, elem) {
elem = $(elem);
if (elem.val().length < 10) {
markDirty(elem);
} else {
markClean(elem);
}
});
$('.discipline').each(function (index, elem) {
elem = $(elem);
if (validDisciplines.indexOf(elem.val()) < 0) {
markDirty(elem);
} else {
markClean(elem);
}
});
}
function markDirty(input) {
input.css({
border: '1px solid red'
});
}
function markClean(input) {
input.css({
border: '1px solid black'
});
}
function toXML(students) {
var xmlString = '<?xml...