2014-04-17 89 views
0

我想通過創建一個數學問題來使用javascript創建一個簡單的驗證碼。這不起作用。任何想法我做錯了什麼?簡單的Javascript OnClick函數不工作

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}"> 
+0

你最好的解決辦法是通過除去聯JavaScript啓動。這將使未來工作變得更容易。然後參考下面提到的代碼......他們基本上都說同樣的事情。 – chrismauck

回答

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}">

+0

您解決了語法錯誤,但if條件將始終爲假,因爲OP使用按鈕值「send」而不是文本框值。 – Hatsjoem

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

0

你的報價是關閉。

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

需求是 的onclick =「如果(值!==‘7’)....

1

您需要刪除雙引號,另外你需要告訴你的條件函數元素珍惜你有興趣。

通過使用JavaScript的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>