简体   繁体   中英

.innerHTML in Javascript

I'm trying to validate a login page with a div to display the errors in , I'm using innerHTML to change the empty text in the div with the error occured , the problem is that the error msg is written and disappears just in a second

here is the code

<html>
<head>
<title>
    Sign up for a membership @ Ay 7aga.com
</title>
<script type="text/javascript">
function check(){
var x = "";
if(document.getElementById('user').value =="")
    x+="Enter user name -";
if(document.getElementById('password').value =="")
    x+="Enter password";
document.getElementById('error1').innerHTML = x;

}
</script>
</head>
<body>
<div name="error" id="error" style="width:1200px;background-color:red"> 
<p name="error1" id="error1"> 
</div>
<center>
<br/>
<form name="register" id="register" >
    <table>
        <tr>
        <td> UserName </td>
            <td> <input type="text" id="user" /> </td>
        </tr>
        <tr>
            <td> Password </td>
            <td> <input type="password" name="password" id="password"/></td>
        </tr>

    </table>
    <button onclick="check()"> Submit </button>
</form>
<a href="Home page.html"> Go to Home page </a>
</center>
</body>
</html>

When using a <button> tag, the "type" attribute is important: most browsers (correctly) default the type to "submit", which makes it work as a form submit element. You can instead set the type to "button", which makes the button have no native behavior other than to fire event handlers. Thus:

Thus:

<button onclick="check()" type=button>Submit</button>

will keep the button from causing an implicit submit of the form.

You are approaching it the wrong way. What is probably happening is that your for is being submitted after click the login button, so that's why the text "disappears" in a couple of seconds.

Put your login checks on the server side, and generate HTML content for that specific scenario instead of using JavaScript.

BTW: what's that <button> tag you are using?

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