基于数组字符串的简单javascript验证码

时间:2014-10-18 07:16:03

标签: javascript jquery arrays

我正在尝试根据我将在数组中更新的字符串创建简单的javascript验证码。

它需要以这种方式工作:

  • 我的数组(看起来像这样:["black", "red", "blue", "green"]
  • 从我的数组中选择一个随机字符串
  • 将在span中选择的随机字符串替换为“请在下一个字段中写下随机字符串
  • 然后查看if ($.trim($(".contact-form input#header-answer").val()) === "random string")

现在我只创建了一个解决方案,它使用一个字符串,而不是我的arra中的随机字符串,这里是:

$(".contact-form form#gform_1").before('<div id="header-question"><span>please write "red" in the next field</span><input id="header-answer" type="text" name=""></div>');

if ($.trim($(".contact-form input#header-answer").val()) === "red") {
  $(".contact-form form#gform_1").submit();
}
else {
  alert('wrong answer try again!');
  return false;
}

1 个答案:

答案 0 :(得分:-1)

虽然我同意上述评论,但我认为标题不正确。这是您正在寻找的一小部分。我再次强调,上述评​​论是正确的,并说这不会成为保护提交内容的安全方式。

var a = ["black", "red", "blue", "green"];
var item = a[Math.floor(Math.random()*a.length)];

$(".contact-form form#gform_1").before('<div id="header-question"><span>please write "' + item + '" in the next field</span></div>');

$(".contact-form form#gform_1").on("submit", function(e) {
    if ($.trim($(".contact-form input#header-answer").val()) === item) {
        //$(".contact-form form#gform_1").submit();
        alert("all good");
    }
    else {
        alert('wrong answer try again!');
        return false;
    }
});

http://jsfiddle.net/L9wcagLr/