OnBeforeUnload如果qty输入是0的不同

时间:2011-07-20 07:33:31

标签: javascript jquery

我有这样的html表:

<table border="1">
  <tr>
    <td>Prod name </td>
    <td>Qty</td>
    <td>Add to cart </td>
  </tr>
  <tr>
    <td>product 1 </td>
    <td><input name="super_group[961]" type="text" class="input-text qty" title="Qty" value="0" size="5" maxlength="12"></td>
    <td><input type="submit" name="Submit" value="Envoyer" /></td>
  </tr>
  <tr>
    <td>product 2 </td>
    <td><input name="super_group[962]" type="text" class="input-text qty" title="Qty" value="0" size="5" maxlength="12"></td>
    <td><input type="submit" name="Submit2" value="Envoyer" /></td>
  </tr>
</table>

我希望避免该用户在数量输入字段中输入数量时退出页面。

(仅当数量字段不为0时我才需要显示消息。)

2 个答案:

答案 0 :(得分:0)

然而https://developer.mozilla.org/en/DOM/window.onbeforeunload

  

请注意,在Firefox 4及更高版本中,返回的字符串不会显示给用户。请参阅Bug 588292

非零时添加AJAX - 未经测试

<html>
  <head>
  <title></title>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
  <script type="text/javascript">
$(window).bind('beforeunload', function(e) { // thanks @Ghostoy for the jquery version of this
  var nonzero = false;
  $(".qty").each(function() { // selector assuming input with class qty
    if (this.value>0) {
      nonzero=true;
      return false; // leave the each
    }
  });
  if (nonzero) return "You have unsaved changes";
});  
$("input[id^='sg_']").each(function() {
  $(this).bind("keyup", function() {
      var disabled = isEmpty(this.value);
      $("#bt_"+this.id.split("_")[1]).attr("disabled",disabled); 
  });
});
$("input[id^='bt_']").each(function() {
  var itemId=this.id.split("_")[1]
  var val = $("#sg_"+itemId).val()
  $(this).attr("disabled",isEmpty(val);
  $(this).click(function() {
      $.get("add_to_cart.php?item="+itemId+"&qty="+$("#sg_"+itemId).val();
  });
});
function isEmpty(val) {
  return isNaN(val() || val=="" || val==null;
}

  </script>
  </head>
  <body>
  <form action="">
  <table border="1">
  <tr>
    <td>Prod name </td>
    <td>Qty</td>
    <td>Add to cart </td>
  </tr>
  <tr>
    <td>product 1 </td>
    <td><input name="super_group[961]" id="sg_961" type="text" class="input-text qty" title="Qty" value="0" size="5" maxlength="12"></td>
    <td><input type="button" id="bt_961" value="Envoyer" /></td>
  </tr>
  <tr>
    <td>product 2 </td>
    <td><input name="super_group[962]" id="sg_962" type="text" class="input-text qty" title="Qty" value="0" size="5" maxlength="12"></td>
    <td><input type="button" id="bt_962" value="Envoyer" /></td>
  </tr>
</table>
</form>
  </body>
</html>

答案 1 :(得分:0)

使用jQuery,您可以:

$(window).bind('beforeunload', function(e) {
    var prompt = false;
    $('input.qty').each(function(i, input) {
      if ($(input).val() != '0') {
          prompt = true;
      }
    });
    if (prompt) {
        return e.returnValue = 'Some warning message';
    }
});