Search code examples
jqueryeachconfirm

JQuery each() function to submit form with confirm


I'm trying to do a confirm dialog using jquery, the form get submitted, but it didn't do the if condition, I had a form .table which contain multiple .profit table. When submit I want it check each salePrice and cost in.profit table column, if cost > salePrice, don't submit, else submit.

The problem is the page always alert the confirm window, I don't know why. this is what I got:

$(".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;
 }});

If the user clicks confirm it would check weather submit the form or not. I hope this makes sense. thanks.

HTML in jsfiddle : https://jsfiddle.net/6jjhmb7L/1/


Solution

  • I try parseInt and add handler,then fix!

    $(".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;
    }});