表单验证"自定义要求"

时间:2017-08-28 01:53:25

标签: javascript html

如何修复此代码?



function shw() {
   document.getElementById('done').style.display = "block";
}

<form name="validation" action="">
<p>what is the capital of England ?</p>
<p>A.London<br>B.Manchester</p>
<input type="text" id="answer" required> 
<button type="submit" value="submit" onclick="shw()">Submit</button>
<!-- If Asnwer is true -->
<!-- All content in form is HIDDEN (Text,input and button), then, show this -->
<div id="done"  style="display:none;" class="answer_list" >Answer Is True</div>

<!-- If Asnwer is wrong/ -->
<!-- All content in form NOT HIDDEN, then, show this in bottom form -->
<div id="done"  style="display:none;" class="answer_list" >Answer Is Wrong</div>
</form>
&#13;
&#13;
&#13; 示例图片:http://www112.zippyshare.com/v/CKwyAAiM/file.html(真答案)
示例图片:http://www112.zippyshare.com/v/Lx7TvOwp/file.html(错误答案)
注意:
- 必须在输入上写伦敦,继续左右。如果答案为真,则表格中的文字,输入和按钮被隐藏,然后显示完整的文字。答案是错的,文字,输入和按钮没有隐藏,显示文字&#34;错误答案&#34;底部形式

1 个答案:

答案 0 :(得分:0)

以下示例代码将进行验证。请注意,所有检查和问题都是根据您提供的示例进行硬编码的。正如JapanGuy在评论中指出的那样,您需要使用一些安全的方法来检查答案。

<form name="validation" action="" id="formName">
    <div id="question">
        <p>what is the capital of England ?</p>
        <p>A.London<br>B.Manchester</p>
        <input type="text" id="answer" required> 
        <button type="submit" value="submit">Submit</button>
    </div>    

    <!-- If Asnwer is true -->
    <!-- All content in form is HIDDEN (Text,input and button), then, show this -->
    <div id="correct"  style="display:none;" class="answer_list" >Answer Is True</div>

    <!-- If Asnwer is true */ -->
    <!-- All content in form NOT HIDDEN, then, show this in bottom form -->
    <div id="wrong"  style="display:none;" class="answer_list" >Answer Is Wrong</div>
</form>

<script>
    var form = document.getElementById("formName");
    form.addEventListener("submit", shw, true);

    function shw(event) {
        event.preventDefault();

        if (document.getElementById("answer").value == "London")
        {
            document.getElementById("question").style.display = "none";
            document.getElementById('correct').style.display = "block";
            document.getElementById('wrong').style.display = "none";
            return true;
        }
        else
        {
            document.getElementById('correct').style.display = "none";
            document.getElementById('wrong').style.display = "block";
            return false;
        }
    }
</script>