阻止表单提交
我试图阻止表单提交并显示警告 DIV,直到他们修复错误的值。 当卖家试图以低于成本价的价格出售产品时,它会显示错误
这是我的
<div class="warnings">error in price</div>
这是我在销售价格低于成本价格时显示的div,所以我们必须阻止他们销售产品
function hide(obj) {
var el = document.getElementById(obj);
el.style.display = 'none';
}
$(document).ready(function() {
$('form#selling').submit(function(e) {
$("#sale_price").mouseout(function() {
if (Number($("#sale_price").val()) <
Number($("#cost_price").val())) {
$("#warnings").show();
}
});
} else {
form.submit();
}
});
});
我没有显示任何错误 DIV,并且表单已提交...
表格有正确的名称和 ID“selling”
表单中的输入是
<input type="hidden" name="sale_price" id="sale_price">
<input type="hidden" name="cost_price" id="cost_price">
最佳答案
我建议在应该阻止提交时返回false
。
否则,即使显示错误,表单仍然会立即提交。
我还纠正了一些其他错误,包括删除 mouseout
,确保所有大括号都已关闭,以及使用 ID 作为错误容器而不是类。
$(function() {
var $cost_price = $('#cost_price');
var $sale_price = $('#sale_price');
var $warnings = $('#warnings');
var $form=$('#selling');
$form.submit(function(e) {
if (Number($sale_price.val()) < Number($cost_price.val())) {
$warnings.fadeIn(150);
return false;
}
});
$form.on('click', function() {
$warnings.fadeOut(150);
});
});
#warnings {
display: none;
margin: 1em 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="selling" action="" method="post">
<input type="text" id="sale_price" value="300">
<input type="text" id="cost_price" value="500">
<input type="submit">
</form>
<div id="warnings">error en precio de venta</div>
关于javascript - 防止表单错误数据和显示错误div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49950383/