[英]Send AJAX request without submitting the form
這個想法是,當用戶填寫預訂信息時,他需要在接收代碼的形式中驗證自己的電話號碼,並在提交之前將其與其余的預訂信息放在一起,所以我有以下觀點
<%= form_for(@booking) do |f| %>
<%= current_or_not_authenticated_user.email %>
<br>
<%= f.label :patient_id %>
<%= f.collection_select :patient_id, User.order(:created_at), :id, :email %>
<button type="button" class="btn btn-primary btn-md" data-toggle="modal" data-target="#patientModal">
New Patient
</button>
<br>
<div class="form-group">
<%= f.label :type %>
<%= f.select :booking_type, options_for_select([['Physiologist'], ['Psychiatrist'], ['Pediatrician']]) %>
<%= f.hidden_field :customer_id, :value => current_or_not_authenticated_user.id %>
</div>
<div class="form-group">
<%= f.label :address %>
<%= f.collection_select :address_id, Address.where(user_id: current_or_not_authenticated_user.id), :id, :address1 %>
<button type="button" class="btn btn-primary btn-md" data-toggle="modal" data-target="#addressModal">
New Address
</button>
<% if current_user && !current_user[:verified_by_phone_at] %>
<div class="form-group">
<%= label_tag(:phone) %>
<%= text_field_tag(:phone) %>
<button id="smsBtn" type="button" class="btn btn-primary">Send SMS</button>
</div>
<div class="form-group">
<%= label_tag :code %>
<%= text_field_tag :code %>
</div>
<% end %>
<%= f.submit "Confirm Booking" %>
</div>
<br>
<% end %>
<script>
$(document).ready(function () {
$('#smsBtn').on('click', function () {
$.ajax({
url: <%=phone_verification_index_path %>,
type: 'ajax',
data: $('#code').val()
});
});
});
</script>
單擊smsbtn應該轉到phone_verification控制器,后者再調用將短信發送給用戶的第三方方法,然后用戶填寫其代碼並單擊Submit。
我的問題是,當用戶單擊smsbtn時,將提交@booking表單,而我不希望表單提交,除非用戶單擊確認預訂(我的jquery工作的唯一方式)是當我同時移動電話字段和smsbtn外部表單。
字段的順序很重要,因為我不希望用戶先查找代碼字段,然后再查找下面的電話字段。
您要防止#smsBtn提交表單,可以用不同的方法來完成,其中之一是在點擊處理程序上調用event.preventDefault()
:
$('#smsBtn').on('click', function (event) {
event.preventDefault()
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.