【问题标题】:Restrict certain postcodes from being entered into form input限制某些邮政编码进入表单输入
【发布时间】:2016-06-21 01:26:40
【问题描述】:

目前正在使用脚本来防止某些邮政编码被输入到相关的输入字段中。

<script>
function checkForm()
{
  var a=document.forms["InsertFrm"]["Postcode"].value;

 if(a == "4001" || "4002") {
  alert("Sorry. This Membership is only available to visitors to the Area!");
  return false;
  }

  }
  </script>

然后在提交表单时,此代码运行.. - 没有问题。

但是,想要更新(仍然使用 jquery) - 输入时会出现警告,而不必等到提交?

【问题讨论】:

  • 请注意标签说明。 jquery-validate 标签仅用于关于 jQuery Validate 插件的问题。已编辑。谢谢。

标签: jquery validation


【解决方案1】:

您使用的是纯 javascript。

你可以使用 jquery 的 keyup 事件来做你需要的事情。

<script>
  function checkForm() {
    var a=document.forms["InsertFrm"]["Postcode"].value;
    // change your condition to this as "4002" is always true
    if(a == "4001" || a == "4002") {
      alert("Sorry. This Membership is only available to visitors to the Area!");
      return false;
    }
  }
  $(document).ready(function() {
    $('input').on('keyup', function(evt) {
      checkForm();
    });
    $('form').on('submit', function(evt) {
      checkForm();
    });
  });
</script>

$('input') 替换为您的输入字段,即$('input#postcode'),将
$('form') 替换为您的输入字段,即$('form#addressform')

您还需要更改您的条件,因为if(a == "4001" || "4002")“4002”将始终为真。必须是if(a == "4001" || a == "4002")

您也可以禁用提交按钮,但这在客户端很容易克服,因此此时使用提交侦听器会更安全。

只是为了好玩,你也可以试试这个:

function checkForm() {
    var a=document.forms["InsertFrm"]["Postcode"].value;
    // change your condition to this as "4002" is always true
    if(a == "4001" || a == "4002") {
      alert("Sorry. This Membership is only available to visitors to the Area!");
      $('input[type=submit]').prop('disabled', true);
      return false;
    } else {
      $('input[type=submit]').prop('disabled', false);
    }
}

【讨论】:

  • 感谢 F - 关闭,但只要我输入任何数字(例如,即使是 1 本身),它就会立即出现警告。
  • 是的,抱歉,您需要更新您的 if 条件。我会更新代码块
  • 抱歉,补充一下,我正在为 Bootstrap 3 使用 Bootstrap 和 Validator v0.10.2,@1000hz
  • 谢谢 F - 好多了。现在,如果输入 4001 或 4002,它实际上不会停止提交表单。访问者可以关闭警告弹出窗口,但仍然继续......我们可以更进一步,这样他们就不能提交了吗?我的不好,也许最初应该提到。原始代码是 onsubmit=blah
  • 使用你的“只是为了好玩”..让我难过,每次我点击弹出窗口上的“关闭”时它都会提交。然后意识到我使用引导
猜你喜欢
  • 2018-11-22
  • 2015-05-28
  • 2011-06-19
  • 1970-01-01
  • 1970-01-01
  • 2015-08-06
  • 1970-01-01
  • 1970-01-01
  • 2015-01-03
相关资源
最近更新 更多