简单的Javascript OnClick功能无法正常工作

时间:2014-04-17 20:23:50

标签: javascript jquery forms validation

我正在尝试通过创建数学问题使用javascript创建一个简单的验证码。这不起作用。对我做错了什么的想法?

What does four + 3 equal? <br>
<input type="text" name="secquestion" id="secquestion" value="" placeholder="Type Numberic Answer Here (Ex. 9)">


 <input type="submit" value="  Send  " class="button" name="button" onclick="if (value !== "7") {alert('You must answer the security question correctly!');return false}">

4 个答案:

答案 0 :(得分:1)

问题是条件语句中使用的双引号会弄乱onclick值周围的双引号。使用这个

<input type="submit" value=" Send " class="button" name="button" onclick="if (value !== '7') {alert('You must answer the security question correctly!');return false}">

答案 1 :(得分:1)

你需要删除双引号,另外你需要告诉你的条件函数你感兴趣的元素值。

通过使用javascripts documentGetElementById,我们可以指定我们感兴趣的文档中的哪个元素。然后我们选择value属性以获取用户的输入并在条件语句中测试它

    What does four + 3 equal? <br>
    <input type="text" name="secquestion" id="secquestion" value="" placeholder="Type Numberic Answer Here (Ex. 9)">


     <input type="submit" value="  Send  " class="button" name="button" onclick="if(document.getElementById('secquestion').value != 7) {alert('You must answer the security question correctly!');return false}">

就个人而言,通过将此条件限制为其自己的函数来维护此代码可能更容易:

    <html>
    What does four + 3 equal? <br>
    <input type="text" name="secquestion" id="secquestion" value="" placeholder="Type Numberic Answer Here (Ex. 9)">


    <input type="submit" value="  Send  " class="button" name="button" onclick="checkCaptcha()">

    <script type="text/javascript">
        function checkCaptcha(){
           if(document.getElementById("secquestion").value != 7){

               alert('You must answer the security question correctly!');

               return false;
           }

           return true;
         }
    </script>
    </html>

答案 2 :(得分:0)

问题只有双引号。

以下代码有效。

What does four + 3 equal? <br>
<input type="text" name="secquestion" id="secquestion" value="" placeholder="Type Numberic Answer Here (Ex. 9)">


 <input type="submit" value="  Send  " class="button" name="button" onclick="if (value !== '7') {alert('You must answer the security question correctly!');return false}">

JSFiddle

答案 3 :(得分:0)

您的报价已关闭。

onclick="if (value !== "7")....

需要     onclick =“if(value!=='7')....