JQuery each() 函数提交表单确认

JQuery each() function to submit form with confirm

我正在尝试使用 jquery 进行确认对话框,表单已提交,但它没有执行 if 条件,我有一个表单 .table,其中包含多个 .profit table。提交时,我希望它检查 .profit table 列中的每个销售价格和成本,if cost > salePrice,不提交,否则提交。

问题是页面总是提示确认window,我不知道为什么。 这是我得到的:

$(".table").submit(function(event) {
  $('.salePrice').each(function() {
  var $table = $(this).parents('.profit');
  var cost = $table.find('.cost').val();
    if( $( this ).val() < cost ) {
      if(confirm("cost is larger than salePrice, are you sure?")){
          result = true;
          return false;
        } else {
          result = false;
          return false;
        }
    }
 });
 if (result) {
    return true;
  }
  else {
    return false;
 }});

如果用户点击确认,它会检查是否提交表单。我希望这是有道理的。谢谢。

HTML 在 jsfiddle 中:https://jsfiddle.net/6jjhmb7L/1/

您的浏览器将这些值解释为字符串(例如:“4.99”)并且比较是在字符串值上进行的,因此它是字母比较而不是数字比较。尝试整合 parseInt。另外,我认为你的逻辑在最后一个 if 语句中是相反的,我在 运行 时遇到了问题,因为 'result' 没有被定义。试试这个:

$(".table").submit(function(event) {
  var result = true;
  $('.salePrice').each(function() {
  var $table = $(this).parents('.profit');
  var cost = parseInt($table.find('.cost').val());
  var price = parseInt($( this ).val());
    if( price < cost ) {
       if(confirm("cost is larger than salePrice, are you sure?")){
          result = true;
          return false;
        } else {
          result = false;
          return false;
        }
    }
 });
 if (!result) {
    return false;
  }
  else {
    return true;
 }
 });

jsFiddle: https://jsfiddle.net/mspinks/xtch7hg8/5/

我尝试 parseInt 并添加处理程序,然后修复!

$(".table").submit(function(event) {
var isOK = true, r = false;

$('.salePrice').each(function() {
  var $table = $(this).parents('.profit');

  var cost = $table.find('.cost').val();

    if (parseInt ($(this).val (), 10) < parseInt (cost, 10)) {
      if (!r) r = confirm ("cost is larger than salePrice, are you sure?");
      isOK = isOK & r;
    }
});

if (isOK) {
  return true;
} else {
  return false;
}});