我正在尝试使用Bootstrap Modal作为表单提交前的确认对话框。但是我想在显示模态之前首先验证我的表单。我怎么能这样做?
这是我到目前为止所尝试的:
<script type="text/javascript">
$(function(){
$(".btn-show-modal").click(function(e){
e.preventDefault();
var id = $(this).attr('id');
var modal_id = "dialog-example_"+id;
$("#"+modal_id).modal('show');
});
$(".btn btn-custom").click(function(e) {
var id = $(this).attr('id');
var modal_id = "dialog-example_"+id;
$("#reservationForm").submit();
$("#"+modal_id).modal('hide');
});
});
</script>
<form class="form" method="POST" action="unit-reservation.php" id="reservationForm">
<div class="form-horizontal">
<div class="control-group">
<label class="control-label"><b>Firstname (*):</b></label>
<div class="controls">
<input type="text" name="customerfname" required />
</div>
</div>
<div class="control-group">
<label class="control-label"><b>Middlename (*):</b></label>
<div class="controls">
<input type="text" name="customermname" required />
</div>
</div>
<div class="control-group">
<label class="control-label"><b>Lastname (*):</b></label>
<div class="controls">
<input type="text" name="customerlname" required />
</div>
</div>
<div class="control-group">
<label class="control-label"><b>Email Address (*):</b></label>
<div class="controls">
<input type="email" name="customeremailaddress" required />
</div>
</div>
<div class="control-group">
<label class="control-label"><b>Address:</b></label>
<div class="controls">
<input type="text" name="customeraddress" required />
</div>
</div>
<div class="control-group">
<label class="control-label"><b>Telephone Number:</b></label>
<div class="controls">
<input type="tel" name="customertelnumber" />
</div>
</div>
<div class="control-group">
<label class="control-label"><b>Mobile Number:</b></label>
<div class="controls">
<input type="number" step="any" min="0" name="customermobilenumber" required /
</div>
</div>
</div>
<input type="hidden" value="<?php echo $user; ?>" name="user_id">
<button id="<?php echo $code; ?>" class="btn btn-custom btn-show-modal" data-toggle="modal">Reserve Now</button>
</form>
<div class="modal hide fade" id="dialog-example_<?php echo $code; ?>">
<div class="modal-header">
<h5>Confirm Reservation</h5>
</div>
<div class="modal-body">
<p class="modaltext">Are you sure you want to reserve unit: <?php echo $code; ?>?</p>
</div>
<div class="modal-footer">
<a href="#" data-dismiss="modal" class="btn">No</a>
<a href="" class="btn btn-custom" id="<?php echo $code ;?>">Yes</a>
</div>
</div>
答案 0 :(得分:0)
问题是,当您点击模态按钮时提交表单,因为它与模态锚点具有相同的类别。
$(".btn-show-modal").click(function(e){ ...
$(".btn btn-custom").click(function(e) {...
您必须为提交的模态锚添加另一个类。
<a href="" class="btn btn-custom btn-submit" id="<?php echo $code ;?>">Yes</a>
并为您的提交点击处理程序调用此方法:
$(".btn-show-modal").click(function(e){ ...
$(".btn-submit").click(function(e){}
像这样,提交动作仅由你的模态锚点触发。如果你使用css样式的类和javascript选择器的相同类,你必须要小心。更好的方法是给这些按钮(如果只使用一次)一个id,这样javascript就可以更快地访问它。并且仅为css保留.btn,.btn-custom。