未触发 Ajax 事件



我正在尝试在填写到达和离开日期时触发 AJAX 事件,但不幸的是没有触发任何内容。如果没有 if 语句,将触发 AJAX 事件。

有什么想法吗?

预订/新.html.erb

<%= simple_form_for [@hotel, @reservation] do |f|%>
<div class="col col-sm-3">
<%= f.input :arrival,
as: :string,
label:false,
placeholder: "From",
wrapper_html: { class: "inline_field_wrapper" },
input_html:{ id: "start_date"} %>
</div>
<div class="col col-sm-3">
<%= f.input :departure,
as: :string,
label:false,
placeholder: "From",
wrapper_html: { class: "inline_field_wrapper" },
input_html:{ id: "end_date"} %>
</div>
<div class="col col-sm-4">
<%= f.input :room_id, collection: @room_categories.order(:name), as: :grouped_select, group_method: :rooms,  label:false %>
</div>
<%= f.button :submit, "Search", class: "create-reservation-btn"%>
<% end %>

预订脚本/新.html.erb

<script>
const checkIn = document.querySelector('#start_date');
const checkOut = document.querySelector('#end_date');
// => if statement that doesn't work
if ((checkIn.value.length > 0) && (checkOut.value.length > 0)){
const checkInAndOut = [checkIn, checkOut];
checkInAndOut.forEach((item) => {
item.addEventListener('change', (event) => {
checkAvailability();
})
})
//}
function checkAvailability(){
$.ajax({
url: "<%= rooms_availability_hotel_path(@hotel) %>" ,
dataType: 'json',
type: "POST",
data: `arrival=${start_date.value}&departure=${end_date.value}`,
success: function(data) {
console.log('succes')
console.log(data);
},
error: function(response) {
console.log('failure')
console.log(response);
}
});
};
</script>

你需要移动你的长度检查

if ((checkIn.value.length > 0) && (checkOut.value.length > 0)){

进入侦听器功能。

因为否则它仅在页面加载时调用,因此会停止侦听器的附件。

最新更新