I am new to javascript, I was creating a form and taking the value from the text box but to cross-check it whether the value is fetched, I used alert inside my js code. it is not showing any alert box while running the code.
I tried to use it without form tag it was working fine.
<html>
<body>
<h2>JavaScript Alert</h2>
<form name="myForm" action="thanks.html" method="get">
UserName:<br/><input type="text" name="user"><br/><br/>
Email:<br/><input type="text" name="pass" id="email"><br/><br/>
Message:<br/><textarea name="msg" rows="5"></textarea><br/><br/>
<input type="submit" name="submit" value="Submit Form" onsubmit="validate()">
</form>
<script>
function validate(){
var email= document.getElementById("email").value;
alert(email);
}
</script>
</body>
</html>
can you please tell me what I am doing wrong
input
element doesn't have onSubmit
event but form
does.
That's all you need to change:
<form name="myForm" action="thanks.html" method="get" onsubmit="validate()">
Demo:
function validate() { var email = document.getElementById("email").value; alert(email); }
<h2>JavaScript Alert</h2> <form name="myForm" action="thanks.html" method="get" onsubmit="validate()"> UserName:<br/><input type="text" name="user"><br/><br/> Email: <br/><input type="text" name="pass" id="email"><br/><br/> Message: <br/><textarea name="msg" rows="5"></textarea><br/><br/> <input type="submit" name="submit" value="Submit Form"> </form>
Change the inout type from "submit" to "button" and then submit your form from validate function using $("#form_id").submit() Also you can try adding e.preventDefault() in validate function.
input has no onSubmit event but form has
function validate(){ var email= document.getElementById("email").value; alert(email); }
<html> <body> <h2>JavaScript Alert</h2> <form name="myForm" action="thanks.html" method="get" onsubmit="validate()"> UserName:<br/><input type="text" name="user"><br/><br/> Email:<br/><input type="text" name="pass" id="email"><br/><br/> Message:<br/><textarea name="msg" rows="5"></textarea><br/><br/> <input type="submit" name="submit" value="Submit Form" > </form> \ </body> </html>
You can use onsubmit="validate()" function in form tag instead input type submit.
<html>
<body>
<h2>JavaScript Alert</h2>
<form name="myForm" action="thanks.html" method="get" onsubmit="validate()">
UserName:<br/><input type="text" name="user"><br/><br/>
Email:<br/><input type="text" name="pass" id="email"><br/><br/>
Message:<br/><textarea name="msg" rows="5"></textarea><br/><br/>
<input type="submit" name="submit" value="Submit Form">
</form>
<script>
function validate(){
var email= document.getElementById("email").value;
alert(email);
}
</script>
</body>
</html>
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.