Я разработал форму, которая помещает видимые и обязательные поля на основе ответа и запроса ajax.Первоначально submitHandler был запущен без проблем, но после некоторого редактирования кода (только часть js) кажется, что он больше не запускается и идет прямо к событию submit, не позволяя мне добавить скрытое поле в запрос.
var API_ENDPOINT = "http://local.test/api";
var isMobile = window.innerWidth < 768;
var profileId = 2;
var childrenCookieSeparator = "|";
$(document).ready(function () {
if (!isMobile) {
$("#request-container").addClass('mobile');
}
// Init datepickers
$.datepicker.setDefaults($.datepicker.regional["it"]);
$('.datepickercheckout').datepicker({
minDate: 1,
dateFormat: "dd/mm/yy",
beforeShowDay:function(date){
if(date.toString().indexOf('Sun ')!=-1) {
return [1, 'weekend'];
} else {
if(date.toString().indexOf('Sat ')!=-1) {
return [1, 'weekend'];
} else {
return [1];
}
}
}
});
$('.datepickercheckin').datepicker({
minDate: 0,
dateFormat: "dd/mm/yy",
onClose: function(dateText,datePickerInstance) {
var oldValue = $(this).data('oldValue') || "";
if (dateText !== oldValue) {
$(this).data('oldValue',dateText);
var from = dateText.split("/")
var dat = new Date(from[2], from[1] - 1, from[0])
dat.setDate(dat.getDate() + 1)
$('.datepickercheckout').datepicker("setDate", dat );
$('.datepickercheckout').datepicker('option', 'minDate', dat);
}
},
beforeShowDay:function(date){
if(date.toString().indexOf('Sun ')!=-1) {
return [1, 'weekend'];
} else {
if(date.toString().indexOf('Sat ')!=-1) {
return [1, 'weekend'];
} else {
return [1];
}
}
}
});
// Init timepickers
$('.timepicker').timepicker({
timeFormat: 'HH:mm',
interval: 30,
dynamic: false,
dropdown: true,
scrollbar: true
});
var firstChild = $('[name="children[]"]');
var removeFirstChild = $('.remove-child');
removeFirstChild.on('click', function (e) {
firstChild.remove();
$(e.target).remove();
});
var form = $("#request-form");
var inputFields = {
'checkin_date': form.find("[name='checkin_date']"),
'checkout_date': form.find("[name='checkout_date']"),
'checkin_time': form.find("[name='checkin_time']"),
'checkout_time': form.find("[name='checkout_time']"),
'name': form.find("[name='name']"),
'email': form.find("[name='email']"),
'phone': form.find("[name='phone']"),
'adults': form.find("[name='adults']"),
'children': form.find("[name='children[]']"),
'additional_requests': form.find("[name='additional_requests']"),
'address': form.find("[name='address']"),
'city': form.find("[name='city']"),
'zip_code': form.find("[name='zip_code']"),
'phone_2': form.find("[name='phone_2']"),
'phone_3': form.find("[name='phone_3']"),
'treatment_id': form.find("[name='treatment_id']")
};
var validation = {
'name': {maxlength: 16},
'email': {maxlength: 255},
'phone': {maxlength: 45},
'adults': {min: 0},
'children[]': {min: 0},
'additional_requests': {maxlength: 255},
'address': {maxlength: 255},
'city': {maxlength: 150},
'zip_code': {maxlength: 16},
'phone_2': {maxlength: 45},
'phone_3': {maxlength: 45}
};
isMobile = isMobile ? 1 : 0;
$.ajax({
url: API_ENDPOINT + "/profiles/" + profileId + "/fields?is_mobile=" + isMobile
})
.done(function (data) {
var fields = data.fields;
fields.push('name', 'email');
var requiredFields = data.required_fields;
requiredFields.push('name', 'email');
var treatments = data.treatments;
var treatmentsSelect = $("#treatment_id");
// Add treatments
for (var id in treatments) {
if (treatments.hasOwnProperty(id)) {
treatmentsSelect.append('<option value="' + id + '">' + treatments[id] + '</option>');
}
}
// Set visible fields
fields.forEach(function (value, index) {
$("#" + value + "_input").show();
if (value === 'children') {
var cookie = Cookies.get('form_children');
if (cookie && cookie !== "") {
// Remove first child
removeFirstChild.click();
// Add other children
var children = cookie.split(childrenCookieSeparator);
children.forEach(function (age) {
addChild(age);
})
}
} else {
inputFields[value].val(Cookies.get("form_" + value));
}
});
// Set required fields
requiredFields.forEach(function (value, index) {
inputFields[value].attr('required', true);
});
// Add other rules to fields
for (var field in validation) {
var input = $('[name="' + field + '"]');
input.prop(validation[field]);
}
if (inputFields.children.prop('required')) {
removeFirstChild.remove();
}
function addChild(age) {
var newChildContainer = $('<div class="children-div"></div>');
var newChildString = '<select id="children_' + i + '" class="input input-children" name="children[]"> ' +
'<option value="0" ' + ((age === "0") ? "selected" : "") + '>0</option> ' +
'<option value="1" ' + ((age === "1") ? "selected" : "") + '>1</option> ' +
'<option value="2" ' + ((age === "2") ? "selected" : "") + '>2</option> ' +
'<option value="3" ' + ((age === "3") ? "selected" : "") + '>3</option> ' +
'<option value="4" ' + ((age === "4") ? "selected" : "") + '>4</option> ' +
'<option value="5" ' + ((age === "5") ? "selected" : "") + '>5</option> ' +
'<option value="6" ' + ((age === "6") ? "selected" : "") + '>6</option> ' +
'<option value="7" ' + ((age === "7") ? "selected" : "") + '>7</option> ' +
'<option value="8" ' + ((age === "8") ? "selected" : "") + '>8</option> ' +
'<option value="9" ' + ((age === "9") ? "selected" : "") + '>9</option> ' +
'<option value="10" ' + ((age === "10") ? "selected" : "") + '>10</option> ' +
'<option value="11" ' + ((age === "11") ? "selected" : "") + '>11</option> ' +
'<option value="12" ' + ((age === "12") ? "selected" : "") + '>12</option> ' +
'<option value="13" ' + ((age === "13") ? "selected" : "") + '>13</option> ' +
'<option value="14" ' + ((age === "14") ? "selected" : "") + '>14</option> ' +
'<option value="15" ' + ((age === "15") ? "selected" : "") + '>15</option> ' +
'<option value="16" ' + ((age === "16") ? "selected" : "") + '>16</option> ' +
'<option value="17" ' + ((age === "17") ? "selected" : "") + '>17</option> ' +
'</select>';
var newChild = $(newChildString);
newChildContainer.append(newChild);
childrenDiv.append(newChildContainer);
}
$("#children_number").change(function() {
var childrenDiv = $("#children");
childrenDiv.empty();
var val = $( this ) . val()
if ( val >= 1) {
var newLabelContainer = $('<div></div>');
var newLabelString = '<label>Quanti anni hanno i bambini con cui viaggi?</label>'
var newLable = $(newLabelString);
newLabelContainer.append(newLable);
childrenDiv.append(newLabelContainer);
}
for(i = 0; i < val; i++) {
var newChildContainer = $('<div class="children-div"></div>');
var newChildString = '<select id="children_' + i + '" class="input input-children" name="children[]"> ' +
'<option value="0" selected>0</option> ' +
'<option value="1">1</option> ' +
'<option value="2">2</option> ' +
'<option value="3">3</option> ' +
'<option value="4">4</option> ' +
'<option value="5">5</option> ' +
'<option value="6">6</option> ' +
'<option value="7">7</option> ' +
'<option value="8">8</option> ' +
'<option value="9">9</option> ' +
'<option value="10">10</option> ' +
'<option value="11">11</option> ' +
'<option value="12">12</option> ' +
'<option value="13">13</option> ' +
'<option value="14">14</option> ' +
'<option value="15">15</option> ' +
'<option value="16">16</option> ' +
'<option value="17">17</option> ' +
'</select>';
var newChild = $(newChildString);
newChildContainer.append(newChild);
childrenDiv.append(newChildContainer);
}
});
// Show form
form.show();
// Validate form on send
form.validate({
submitHandler: function (nativeForm) {
nativeForm.append('<input type="hidden" name="user_id" value="' + profileId + '"/>');
// Save cookies
fields.forEach(function (value, index) {
var val = inputFields[value].val();
// Save every child
if (value === 'children') {
val = [];
form.find("[name='children[]']").each(function (i, c) {
val.push($(c).val());
});
val = val.join(childrenCookieSeparator);
}
Cookies.set("form_" + value, val);
});
nativeForm.submit();
}
});
})
.fail(function (jqXHR, data) {
console.log(data);
});
});
Форма выглядит следующим образом:
<div id="request-container">
<form style="display: none" id="request-form" action="http://local.test/api/requests" method="POST">
<div style="display: none" id="checkin_date_input">
<input id="checkin_date" class="input datepickercheckin" name="checkin_date" placeholder="Check-in" />
</div>
<div style="display: none" id="checkin_time_input">
<input id="checkin_time" class="input timepicker" name="checkin_time" placeholder="Orario di check-in" />
</div>
<div style="display: none" id="checkout_date_input">
<input id="checkout_date" class="input datepickercheckout" name="checkout_date" placeholder="Check-out" />
</div>
<div style="display: none" id="checkout_time_input">
<input id="checkout_time" class="input timepicker" name="checkout_time" placeholder="Orario di check-out" />
</div>
<div style="display: none" id="name_input">
<input class="input" id="name" name="name" type="text" placeholder="Nome" />
</div>
<div style="display: none" id="email_input">
<input class="input" id="email" name="email" type="email" placeholder="E-mail" />
</div>
<div style="display: none" id="phone_input">
<input class="input" id="phone" name="phone" placeholder="Telefono" />
</div>
<div style="display: none" id="adults_input">
<select id="adults" class="input" name="adults">
<option value="" disabled selected>Adulti</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
</select>
</div>
<div style="display: none" id="children_input">
<select id="children_number" class="input" name="children_number">
<option value="" disabled selected>Bambini</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<div id="children">
</div>
</div>
<div style="display: none" id="address_input">
<input class="input" id="address" name="address" placeholder="Indirizzo" />
</div>
<div style="display: none" id="city_input">
<input class="input" id="city" name="city" placeholder="Città" />
</div>
<div style="display: none" id="zip_code_input">
<input class="input" id="zip_code" name="zip_code" placeholder="CAP" />
</div>
<div style="display: none" id="phone_2_input">
<input class="input" id="phone_2" name="phone_2" placeholder="Telefono (2)" />
</div>
<div style="display: none" id="phone_3_input">
<input class="input" id="phone_3" name="phone_3" placeholder="Telefono (3)" />
</div>
<div style="display: none" id="treatment_id_input">
<select class="input" id="treatment_id" name="treatment_id">
<option value="" disabled selected>Trattamento</option>
</select>
</div>
<div style="display: none" id="additional_requests_input">
<textarea id="additional_requests" name="additional_requests" class="input"
placeholder="Richieste aggiuntive"
></textarea>
</div>
<input type="checkbox" id="privacy" checked required> Privacy policy
<button id="request-form-send" type="submit">Invia richiesta</button>
</form>
</div>
<link rel="stylesheet" type="text/css" href="request.css">
<script src="request.js"></script>
Я уже пытался поместить точку останова и консольный журнал в обработчик отправки, и он не работает.Я также пытался изменить кнопку отправки в элементе ввода со значением «submit», но она также не работает.