javascript - 防止表单错误数据和显示错误div

标签 javascript jquery html

阻止表单提交

我试图阻止表单提交并显示警告 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/

相关文章:

javascript - 捕获跨源 iframe 事件

javascript - 使用 jquery canvas 元素显示隐藏的 div

javascript - fatal error : invalid array length Allocation failed - JavaScript heap out of memory

javascript - Slick Carousel - 设置第一张幻灯片

javascript - 使用 Jquery 动态加载新内容

javascript - 在新选项卡中提交表单并将现有页面重定向到 xyz.html

jquery - 在 jQuery 中,我如何将左对齐样式附加到所有元素?

javascript - 仅选择一组中的一个复选框,但如果是某些复选框,则可以选择多个复选框

javascript - 比较预先声明和自调用的匿名函数

jquery - 无法在jquery中找到单选按钮点击事件