简体   繁体   中英

Simple Javascript Validation not working

I am trying to do the following:

HTML Code

<body>
    <form name="myform">
    <table>
        <tr>
            <td>First Name:</td>
            <td><input type="text" id="first_name"></td>
            <td><p id="demo"></p></td>
        </tr>
        <tr>
            <td><input type="submit" id="Submit" onclick="validate()"></td>
        </tr>
    </form></body>

JavaScript Code

<script>
    function validate(){

        var fname = document.getElementById("first_name").value;
        if(fname.length>0){
            document.getElementById("demo").value="";
        }
        else{
            document.getElementById("demo").value="Name field empty";
        }
    }
    </script>

when I click the button with the empty First name field it should assign "name field empty" but it does not do that even though the control of the script goes there but it does not print anything in the <p> tag.

I think you should try this instead :D

<script>
    function validate(){

        var fname = document.getElementById("first_name").value;
        if(fname!=""){
            document.getElementById("demo").innerHTML="";
        }
        else{
            document.getElementById("demo").innerHTML="Name field empty";
        }
    }
    </script>

You wanna check if the field is empty or not so in this case the fname is enough to use all along. If the variable fname (which is the first_name field's value) is not empty then it proceed the statement that will set the HTML content of "demo" to "" with .innerHTML . The .value you used has nothing to do with the display HTML content relating to demo :D. I hope my English is not that bad for you to understand this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM