Javascript只会在字段中产生1个字符

时间:2019-01-23 03:29:21

标签: javascript jquery html css

我有一个脚本,可在单击按钮时生成10个字符的代码。我想将代码移植到输入文本框的value字段中。我认为这是有冲突的,因为该文本框位于附加了click(function(event) {的表单内。

HTML / CSS

    <div id="add_wrap">
<form method="post" action="voucher_add_post.php">
  <table width="100%" border="0" cellspacing="2" cellpadding="2">
    <tr>
      <td>Voucher value: </td>
      <td><input type="text" id="value" size="10"></td>
    </tr>
    <tr>
      <td>Code</td>
      <td><input type="text" id="code" size="20"> <button id="generate">Generate</button></td>
    </tr>
    <tr>
      <td>How many vouchers?</td>
      <td><input type="text" id="amount" placeholder="Leave blank for only one voucher" size="40"></td>
    </tr>
    <tr>
        <td>&nbsp;</td>
    <td><input type="submit" id="submit" value="Submit" /></td>
    </tr>
  </table>
</form>
<div id="message"></div>
</div>

Javascript / JQuery

<script>
  $("#submit").click(function(event) {
    event.preventDefault();

    var headline = $('#headline').val();
    var author = $('#author').val();
    var details = $('#details').val();
    var question = $('#question').val();
    var reward_img = $('#reward_img').val();
    var reward_cap = $('#reward_cap').val();
    var days = $('#days').val();

    $.ajax({
      type: "POST",
      url: "pages/comp_add_post.php",
      data: "headline="+headline+"&author="+author+"&details="+details+
            "&question="+question+"&reward_img="+reward_img+"&reward_cap="+reward_cap+"&days="+days,
      success: function(data){
        $("#message").html(data);
      }

    });
    });

    $("#generate").click(function(event) {
      event.preventDefault();

      function codeGen(length)
      {
        var code = "";
        var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        for (var i=0; i<length; i++);
          code += chars.charAt(Math.floor(Math.random() * chars.length));

        return code;
      }
      $("#code").val(codeGen(10));
    });
</script>

问题在于它仅在ID为value=的输入框的generate属性中生成一个字符。

如果我使用onClick="codeGen()"方法,那么它将提交表单。

2 个答案:

答案 0 :(得分:4)

我认为问题出在您的for循环中。您目前将其写为:

for (var i=0; i<length; i++);
code += chars.charAt(Math.floor(Math.random() * chars.length));

但是;循环声明之后的for终止了该语句。如果您将其重写为:

for (var i = 0; i < length; i++) {
   code += chars.charAt(Math.floor(Math.random() * chars.length));
}

似乎可行。

提琴:https://jsfiddle.net/s3ndkpue/

答案 1 :(得分:0)

使用半冒号的for循环是问题,但是我也将尝试简化JS + Jquery,以便于阅读,如下所示:

$("#generate").click(function(event) {
  event.preventDefault();

  var code = "";
  var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for (var i=0; i < 10; i++)
      code += chars.charAt(Math.floor(Math.random() * chars.length));

  $("#code").val(code);
});

希望有帮助:)