无法从表单(JS)接收值

时间:2019-02-07 19:53:00

标签: javascript html forms

我是Java的新手,所以我研究了一些如何从基本HTML表单中提取值和字符串的方法。不管我做什么,我似乎都无法提出任何价值观。最初,我尝试使用ID,并使用var x = document.getElementById(“ variablegoeshere”);为每个ID分配一个变量。但这没用。然后尝试使用名称,并在表单列周围添加表单标签,从此演示中进行复制:https://www.w3schools.com/js/tryit.asp?filename=tryjs_validation_js

那也不起作用。任何帮助将不胜感激。上下文的所有代码:

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width">
        <!-- Bootstrap CSS Import -->
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
        <!-- Bootstrap JS, JQuery and Popper.JS Import -->
        <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
		<script>
            //Image Background Randomizer
            $(document).ready(function(){
                var images=['https://images.pexels.com/photos/753639/pexels-photo-753639.jpeg?auto=compress&cs=tinysrgb&dpr=2',
                'https://images.pexels.com/photos/10922/pexels-photo-10922.jpeg?auto=compress&cs=tinysrgb&dpr=1',
                'https://images.pexels.com/photos/1797158/pexels-photo-1797158.jpeg?auto=compress&cs=tinysrgb&dpr=1',
                'https://images.pexels.com/photos/532263/pexels-photo-532263.jpeg?auto=compress&cs=tinysrgb&dpr=1',
                'https://images.pexels.com/photos/227517/pexels-photo-227517.jpeg?auto=compress&cs=tinysrgb&dpr=1',
                'https://images.pexels.com/photos/531602/pexels-photo-531602.jpeg?auto=compress&cs=tinysrgb&dpr=2',
                'https://images.pexels.com/photos/1796736/pexels-photo-1796736.jpeg?auto=compress&cs=tinysrgb&dpr=2'];
                var randomNumber = Math.floor(Math.random() * images.length);
                var bgImg = 'url(' + images[randomNumber] + ')';
                $('body').css({'background':bgImg, 'background-size':'cover', });
            });
            //Info Compiler Code
            function validateForm() {
            var x = document.forms["myForm"]["lintoe1"]["noun"]["verb"]["tenses1"]["isroot1"]["nonroot1"]["cases1"].value;
            if (x == "") {
                alert("Name must be filled out");
                return false;
            } else {
                alert(x);
            }
            }
            function lintoe() {
                var lintoe1=document.getElementById=("lintoe1");
                var noun=document.getElementById=("noun");
                var verb=document.getElementById=("verb");
                var tenses1=document.getElementById=("tenses1");
                var isroot1=document.getElementById=("isroot1");
                var nonroot1=document.getElementById=("nonroot1");
                var cases1=document.getElementById=("cases1");
                alert(lintoe1+noun+verb+tenses1+isroot1+nonroot1+cases1);
                var lintoecomplete=document.getElementById=("lintoecomplete").innerHTML=("");
            }
        </script>
		<style>
            @import url('https://fonts.googleapis.com/css?family=Krub:500');
            html, body {
                width: 100vw;
                height: 100vh;
                margin: 0;
                padding: 0;
                overflow-x: hidden; 
                max-width: 100%;
            }
            body { 
                /* Background */
                background: no-repeat center center fixed; 
                background-size: cover;
                background-repeat: no-repeat;
                width: 100vw;
                height: 100vh;
                font-family: Krub, Arial, Helvetica, sans-serif;
            }
            @-webkit-keyframes animation11 {
                0% {width: 100%;}
                100% {width: 0%;}
            }
            @-moz-keyframes animation11 {
                0% {width: 100%;}
                100% {width: 0%;}
            }
            @-o-keyframes animation11 {
                0% {width: 100%;}
                100% {width: 0%;}
            }
            @keyframes animation11 {
                0% {width: 100%;}
                100% {width: 0%;}
            }
            #animation1 {
                -webkit-animation: animation11 5s infinite ease-in-out both alternate-reverse;
                -moz-animation: animation11 5s infinite ease-in-out both alternate-reverse;
                -o-animation: animation11 5s infinite ease-in-out both alternate-reverse;
                animation: animation11 5s infinite ease-in-out both alternate-reverse;
            }
            .jumbotron {
                border-radius: 0px;
                background-color: rgb(255,255,255,0.25);
                height: auto;
                padding-top: 10vh;
                width: 100vw;
            }
            .col-sm {
                border-radius: 30px;
                background-color: rgb(255,255,255,0.75);
                border-left: 6px solid rgb(0,0,0,0.25);
            }
            .navigationbar {
                background-color:rgb(0,0,0,0.9);
                color: white; 
                margin-top: -5.8vh;
            }
            .tab-content {padding: 10vh 10vw 10vh 10vw;}
            .whitething {color: white;}
        </style>
        <link rel="icon" href="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSsBP3sbu95lAKZwOv6AfvsLWfU_f62LMPucDUgxIh0Yswcp4wopQ:https://comps.canstockphoto.com/golden-gladiator-helmet-logo-image_csp50693170.jpg" type="image/x-icon"/>
        <link rel="shortcut icon" href="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSsBP3sbu95lAKZwOv6AfvsLWfU_f62LMPucDUgxIh0Yswcp4wopQ:https://comps.canstockphoto.com/golden-gladiator-helmet-logo-image_csp50693170.jpg" type="image/x-icon"/>
        <title>Latin Translator / Conjugator</title>
    </head>
    <body>
        <div class="jumbotron text-center">
            <i>
                <h1>Latin Translator / Conjugator</h1>
                <br>
                <p>Fill in the fields to find translated / conjugated verb or noun.</p>
                <br>
                <hr id="animation1">
                <br>
            </i>
            <div class="container">
                <div class="row">
                    <div class="col-sm">
                        <form name="myForm" onsubmit="return validateForm()" method="post">
                            <br>
                            <h3><i>Latin Into English</i></h3>
                            <hr>
                            <form>
                                <div class="form-group">
                                    <p>Word Input</p>
                                    <input type="text" class="form-control" name="lintoe1" placeholder="Enter Word Here">
                                </div>
                            </form>
                            <hr>
                            <p>Is this word a Noun or a Verb?</p>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="noun" value="option1">
                                <label class="form-check-label" for="noun">Noun</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="checkbox" name="verb" value="option2">
                                <label class="form-check-label" for="verb">Verb</label>
                            </div>
                            <hr>
                            <p>Select Tense.</p>
                            <div class="dropdown mr-1">
                                <button class="btn btn-dark btn-block dropdown-toggle" id="tenses10" data-toggle="dropdown" aria-expanded="false">Tenses</button>
                                <div class="dropdown-menu" aria-labelledby="tenses10" name="tenses1">
                                    <a class="dropdown-item" href="#">Imperfect</a>
                                    <a class="dropdown-item" href="#">Perfect</a>
                                    <a class="dropdown-item" href="#">Present</a>
                                    <a class="dropdown-item" href="#">Future</a>
                                    <a class="dropdown-item" href="#">Imperative</a>
                                </div>
                            </div>
                            <hr>
                            <p>Is this the root of the word? If not, give root.</p>
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <div class="input-group-text">
                                        <input class="form-check-input" type="checkbox" name="isroot1">
                                        <label class="form-check-label" for="isroot1">This is the root.</label>
                                    </div>
                                </div>
                                <input type="text" class="form-control" name="nonroot1">
                            </div>
                            <hr>
                            <p>If word is noun, give case.</p>
                            <div class="dropdown mr-1">
                                <button class="btn btn-secondary btn-block dropdown-toggle" id="cases10" data-toggle="dropdown" aria-expanded="false">Cases</button>
                                <div class="dropdown-menu" aria-labelledby="cases10" name="cases1">
                                    <a class="dropdown-item" href="#">Nominative</a>
                                    <a class="dropdown-item" href="#">Accusative</a>
                                    <a class="dropdown-item" href="#">Genetive</a>
                                    <a class="dropdown-item" href="#">Dative</a>
                                    <a class="dropdown-item" href="#">Ablative</a>
                                    <a class="dropdown-item" href="#">Not a Verb</a>
                                </div>
                            </div>
                            <hr>
                            <button class="btn btn-block btn-outline-dark" type="submit" value="Submit">Confirm</button>
                        </form>
                        <hr>
                        <div id="accordion">
                            <div class="card">
                                <div class="card-header" id="headingOne">
                                    <p class="mb-0"><button class="btn btn-link" data-toggle="collapse" data-target="#lintoejs" aria-controls="lintoejs" id="lintoecomplete">Answer</button></p>
                                </div>
                                <div id="lintoejs" class="collapse" data-parent="#accordion">
                                    <div class="card-body">
                                        <p>Please finish completing your forms.</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <br><br>
                    </div>

唯一重要的部分是

function validateForm() {
            var x = document.forms["myForm"]["lintoe1"]["noun"]["verb"]["tenses1"]["isroot1"]["nonroot1"]["cases1"].value;
            if (x == "") {
                alert("Name must be filled out");
                return false;
            } else {
                alert(x);
            }
            }
            function lintoe() {
                var lintoe1=document.getElementById=("lintoe1");
                var noun=document.getElementById=("noun");
                var verb=document.getElementById=("verb");
                var tenses1=document.getElementById=("tenses1");
                var isroot1=document.getElementById=("isroot1");
                var nonroot1=document.getElementById=("nonroot1");
                var cases1=document.getElementById=("cases1");
                alert(lintoe1+noun+verb+tenses1+isroot1+nonroot1+cases1);
                var lintoecomplete=document.getElementById=("lintoecomplete").innerHTML=("");
            }

(为澄清起见,lintoe()函数仅在将所有名称都更改为ID并且按钮具有链接到lintoe()的onclick函数时起作用):

<div class="container">
                <div class="row">
                    <div class="col-sm">
                        <form name="myForm" onsubmit="return validateForm()" method="post">
                            <br>
                            <h3><i>Latin Into English</i></h3>
                            <hr>
                            <form>
                                <div class="form-group">
                                    <p>Word Input</p>
                                    <input type="text" class="form-control" name="lintoe1" placeholder="Enter Word Here">
                                </div>
                            </form>
                            <hr>
                            <p>Is this word a Noun or a Verb?</p>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="noun" value="option1">
                                <label class="form-check-label" for="noun">Noun</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="checkbox" name="verb" value="option2">
                                <label class="form-check-label" for="verb">Verb</label>
                            </div>
                            <hr>
                            <p>Select Tense.</p>
                            <div class="dropdown mr-1">
                                <button class="btn btn-dark btn-block dropdown-toggle" id="tenses10" data-toggle="dropdown" aria-expanded="false">Tenses</button>
                                <div class="dropdown-menu" aria-labelledby="tenses10" name="tenses1">
                                    <a class="dropdown-item" href="#">Imperfect</a>
                                    <a class="dropdown-item" href="#">Perfect</a>
                                    <a class="dropdown-item" href="#">Present</a>
                                    <a class="dropdown-item" href="#">Future</a>
                                    <a class="dropdown-item" href="#">Imperative</a>
                                </div>
                            </div>
                            <hr>
                            <p>Is this the root of the word? If not, give root.</p>
                            <div class="input-group">
                                <div class="input-group-prepend">
                                    <div class="input-group-text">
                                        <input class="form-check-input" type="checkbox" name="isroot1">
                                        <label class="form-check-label" for="isroot1">This is the root.</label>
                                    </div>
                                </div>
                                <input type="text" class="form-control" name="nonroot1">
                            </div>
                            <hr>
                            <p>If word is noun, give case.</p>
                            <div class="dropdown mr-1">
                                <button class="btn btn-secondary btn-block dropdown-toggle" id="cases10" data-toggle="dropdown" aria-expanded="false">Cases</button>
                                <div class="dropdown-menu" aria-labelledby="cases10" name="cases1">
                                    <a class="dropdown-item" href="#">Nominative</a>
                                    <a class="dropdown-item" href="#">Accusative</a>
                                    <a class="dropdown-item" href="#">Genetive</a>
                                    <a class="dropdown-item" href="#">Dative</a>
                                    <a class="dropdown-item" href="#">Ablative</a>
                                    <a class="dropdown-item" href="#">Not a Verb</a>
                                </div>
                            </div>
                            <hr>
                            <button class="btn btn-block btn-outline-dark" type="submit" value="Submit">Confirm</button>
                        </form>
                        <hr>
                        <div id="accordion">
                            <div class="card">
                                <div class="card-header" id="headingOne">
                                    <p class="mb-0"><button class="btn btn-link" data-toggle="collapse" data-target="#lintoejs" aria-controls="lintoejs" id="lintoecomplete">Answer</button></p>
                                </div>
                                <div id="lintoejs" class="collapse" data-parent="#accordion">
                                    <div class="card-body">
                                        <p>Please finish completing your forms.</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <br><br>
                    </div>

对不起,如果我好像不知道自己在做什么,但我真的不知道...

1 个答案:

答案 0 :(得分:0)

首先

document.forms["myForm"]["lintoe1"]["noun"]["verb"]["tenses1"]["isroot1"]["nonroot1"]["cases1"].value

不起作用。您需要执行以下操作:

document.forms["myForm"]["lintoe1"].value
document.forms["myForm"]["noun"].value
document.forms["myForm"]["verb"].value

在您的示例中,执行forms["myForm"]["lintoe1"]["noun"]会尝试获得"noun"的名称"lintoe1",但是它们处于同一级别。换句话说,"noun"中没有"lintoe1"元素。

我注意到的另一件事是

var lintoe1=document.getElementById=("lintoe1");

也不起作用,您应该删除第二个=

var lintoe1=document.getElementById("lintoe1");

此外,您实际上并不需要这两行:

var x = document.forms["myForm"]["lintoe1"].value;

var lintoe1=document.getElementById("lintoe1").value;

它们是等效的,您将获得完全相同的值。主要区别在于,当您使用getElementById时,Javascript将遍历整个DOM及其所有div / elements以查找所需的元素。通过使用document.forms["myForm"],最好指定Javascript应该查找哪个元素(form)及其名称(myForm)。

更好的validateForm()是:

function validateForm() {
    var lintoe1=document.getElementById("lintoe1").value;
    var noun=document.getElementById("noun").value;
    var verb=document.getElementById("verb").value;
    [ more code here ];

    if (lintoe1 && noun && verb && ....) {
        alert("All fields must be filled");
        return false;
    } else {
        alert(x);
    }
}

以上方法之所以有效,是因为document.getElementById("lintoe1").value将返回该值(如果存在)或undefined(如果不存在)。

如果设置了所有值,if (lintoe1 && noun && verb && ....)将返回true;否则,将返回true。如果其中任何一个是undefined,它将返回false。

请注意,有更好的方法来验证表单,特别是使用其他库。

而且,正如安迪(Andy)所说,you shouldn't have nested forms

  

4.10.3 form元素

     

内容模型:

     

流内容,但没有表单元素后代。

相关问题