我发现此JavaScript可以计算(在表单提交时)所有带有class =“ qt”的输入字段的总和。如果所有字段的总和小于15,则会在javascript警报弹出窗口中显示一条消息。到目前为止,一切都很好。 但是我不喜欢Javascript警报弹出窗口的样式,而且似乎无法设置样式。因此,我想在标准样式对话框中显示消息,而不是标准的Javascript警报弹出窗口。到目前为止还算不错。 我唯一不知道的是如何将Javascript变量(sum)的值带入模态窗口并在那里显示它。
表单标签:
<form onsubmit="return calculateSum(this);" method="post" name="order" id="order" action="confirm.php">
Javascript(外部文件:javascript.js):
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".qt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
if(sum<15) {
//alert('Please order at least 15 boxes.\n\nYour current selection is ' + sum + '.');
$(document).ready(function(){$("#myModal").modal("show"); });
return false;
}
else {
return true;
//return confirm('Do you really want to submit the form?');
}
}
显示(html)的(Bootstrap)模式:
<!-- The Modal -->
<div class="modal fade" id="myModal">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<!--HOW CAN I SHOW THE JAVASCRIPT VARIABLE (sum) HERE?-->
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
答案 0 :(得分:0)
在模式HTML中添加一个空的<p>
标记(或者您希望在模式中显示它),并为其提供一个id
,供您在Javascript中使用。然后,将脚本中标记的innerHTML
替换为变量:
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".qt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
if(sum<15) {
//alert('Please order at least 15 boxes.\n\nYour current selection is ' + sum + '.');
$(document).ready(function(){$("#myModal").modal("show"); });
return false;
}
else {
return true;
//return confirm('Do you really want to submit the form?');
}
document.getElementById('sum').innerHTML=sum;
}
}
<!-- The Modal -->
<div class="modal fade" id="myModal">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<!--HOW CAN I SHOW THE JAVASCRIPT VARIABLE (sum) HERE?-->
<p id="sum"></p>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
答案 1 :(得分:0)
您可以在准备好的回调中插入消息:
$(document).ready(function() {
$(".modal-body").html("Please order at least 15 boxes.\n\nYour current selection is " + sum + ".");
$("#myModal").modal("show");
});