Multiple forms relating to Javascript in one WEB-page - javascript

I want to have two forms on the same page, one for userregistration, and one for editing a comanys name. This is how I have gotten so far...
test001.js:
$(document).ready(function() {
$(function() {
$("#dialog").dialog({
autoOpen: false
});
$("#button").on("click", function() {
$("#dialog").dialog("open");
});
});
// Validating Form Fields.....
$("#submit").click(function(e) {
var email = $("#email").val();
var comnpanyname = $("#companyname").val();
var lastname = $("#lastname").val();
var password = $("#password").val();
var emailReg = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
if (firstname === '' || lastname === '' || password === '' || email === '') {
alert("Please fill all fields!");
e.preventDefault();
} else if (!(email).match(emailReg)) {
alert("Invalid Email!");
e.preventDefault();
} else {
alert("Form Submitted Successfully.");
}
});
});
test001.css
#import "http://fonts.googleapis.com/css?family=Droid+Serif";
/* Above line is used for online google font */
h2 {
text-align:center;
font-size:24px
}
hr {
margin-bottom:30px
}
p {
color:#000;
font-size:16px;
font-weight:700
}
#button,#button2 {
border:1px solid #0c799e;
width:250px;
padding:10px;
font-size:16px;
font-weight:700;
color:#fff;
border-radius:3px;
background:linear-gradient(to bottom,#59d0f8 5%,#49c0e8 100%);
cursor:pointer
}
#button:hover,#button2:hover {
background:linear-gradient(to bottom,#49c0e8 5%,#59d0f8 100%)
}
input[type=text] {
margin-top:5px;
margin-bottom:20px;
width:96%;
border-radius:5px;
border:0;
padding:5px 0
}
#firstname,#lastname,#email,#password,#company {
padding-left:10px
}
input[type=submit] {
width:30%;
border:1px solid #59b4d4;
background:#0078a3;
color:#eee;
padding:3px 0;
border-radius:5px;
margin-left:33%;
cursor:pointer
}
input[type=submit]:hover {
border:1px solid #666;
background:#555;
color:#fff
}
.ui-dialog .ui-dialog-content {
padding:2em
}
/* 960x610 */
div.container {
width:500px;
height:300px;
margin:50px auto;
font-family:'Droid Serif',serif;
position:relative
}
div.container2 {
width:960px;
height:610px;
margin:50px auto;
font-family:'Droid Serif',serif;
position:relative
}
div.main {
width:320px;
margin-top:35px;
float:left;
padding:10px 55px 25px;
background-color:rgba(204,204,191,0.51);
border:15px solid #fff;
box-shadow:0 0 10px;
border-radius:2px;
font-size:13px;
text-align:center
}
div.main2 {
width:320px;
margin-top:35px;
float:left;
padding:10px 55px 25px;
background-color:rgba(204,204,191,0.51);
border:15px solid #fff;
box-shadow:0 0 10px;
border-radius:2px;
font-size:13px;
text-align:center
}
<!DOCTYPE html>
<html>
<head>
<title>jQuery Dialog Form Example</title>
<link href="http://enersen.no/development/eds/css/test001.css" rel="stylesheet">
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/ui-darkness/jquery-ui.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<script src="http://enersen.no/development/eds/js/user.js" type="text/javascript"></script>
<!-- script src="http://enersen.no/development/eds/js/company.js" type="text/javascript"></script -->
</head>
<body>
<div class="container">
<div class="main">
<div id="dialog" title="Dialog Form">
<form action="" method="post">
<label>First name:</label>
<input id="firstname" name="firstname" type="text">
<label>Last name:</label>
<input id="lastname" name="lastname" type="text">
<label>Email:</label>
<input id="email" name="email" type="text">
<label>Password:</label>
<input id="password" name="password" type="password">
<input id="submit" type="submit" value="Submit">
</form>
</div>
<h2>jQuery Dialog Form Example</h2>
<p>Click below button to see jQuery dialog form.</p>
<input id="button" type="button" value="Open Dialog Form">
</div>
</div>
<div class="container2">
<div class="main2">
<div id="dialog2" title="Dialog Form 2">
<form action="" method="post">
<label>New comany name:</label>
<input id="company" name="company" type="text">
<input id="submit" type="submit" value="Submit">
</form>
</div>
<h2>jQuery Dialog Form Example</h2>
<p>Click below button to see jQuery dialog form.</p>
<input id="button2" type="button" value="Open Company Dialog Form">
</div>
</div>
</body>
</html>
I expect the form that I activate to be the one evaluated. Now it is the form for adress-/login-info that gets evaluated. I guess I need some code snipplet that lets med deal with the forms as different documents in Javascript?

You have more than one submit button with the id submit - simply change them to be unique - where you use an id attribute, they should always be unique for the page.
For example, use userRegistrationSubmit for one and then change this:
$("#submit").click(function(e) {
to
$("#userRegistrationSubmit").click(function(e) {
You could call the other companyNameChangeSubmit.

Thanks, Jamiec, you pointed me in the rigth direction and I solved it :-) Here's the result:
$(document).ready(function() {
$(function() {
$("#userDialog").dialog({
autoOpen: false
});
$("#companyDialog").dialog({
autoOpen: false
});
$("#userButton").on("click", function() {
$("#userDialog").dialog("open");
});
$("#companyButton").on("click", function() {
$("#companyDialog").dialog("open");
});
});
// Validating Form Fields.....
$("#userSubmit").click(function(e) {
var email = $("#email").val();
var comnpanyname = $("#companyname").val();
var lastname = $("#lastname").val();
var password = $("#password").val();
var emailReg = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
if (firstname === '' || lastname === '' || password === '' || email === '') {
alert("Please fill all fields!");
e.preventDefault();
} else if (!(email).match(emailReg)) {
alert("Invalid Email!");
e.preventDefault();
} else {
alert("Form Submitted Successfully.");
}
});
});

Related

How to put a tooltip on input when its not valid

I want to show a tooltip on ma text input when it's not valid
function check() {
var ok = true;
regLast = /^[a-zA-Z]{2,20}$/;
if (!regLast.test(document.getElementById("lastName").value)) {
ok = false;
}
return ok;
}
<div class="form-group">
<label for="lastName">Last name:</label>
<input type="text" class="form-control" id="lastName" placeholder="Put your last name" name="lastName" />
</div>
and I know how to put, a text in a div under, a input by document.getElementById("wronglastnamediv").innerHTML = "Put valid last name"
But I don't know how to put a tooltip on these text area when it's not valid..
You should edit the below code accordingly, also link the jquery 1.7 or above-
<script>
$('#lastName').on('keyup', function () {
$('.text-error').remove();
var ok=true;
regLast = /^[a-zA-Z]{2,20}$/;
if (!regLast.test(document.getElementById("lastName").value))
{
ok=false;
$(this).parent('.form-group').append("<span class='text-error'>Please enter a valida string.</span>");
}
return ok;
});
</script>
//CSS add your own CSS for tooltip style etc
<style type="text/css">
.form-group{
position:relative;
}
.text-error{
position:absolute;
right:0;
top:0px;
background:red;
color:white;
border-radius:5px;
padding:5px 3px;
}
</style>
Hopefully the code will work for you.
Pure Javascript
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
.form-control{
position:relative;
width: 100%;
float: left;
}
.text-error{
position:absolute;
right:0;
top:0px;
background:red;
color:white;
border-radius:5px;
padding:5px 3px;
display: none;
}
.display_block{
display: block;
}
</style>
</head>
<body>
<div class="form-group">
<label for ="lastName">Last name:</label>
<input type = "text" class = "form-control" id = "lastName" onkeyup="check()" placeholder = "Put your last name" name = "lastName" />
<span class="text-error" id="error_lastname"></span>
</div>
<script type="text/javascript">
function check () {
var div = document.getElementById("error_lastname");
div.setAttribute('class', 'text-error');
var ok=true;
regLast = /^[a-zA-Z]{2,20}$/;
if (!regLast.test(document.getElementById("lastName").value))
{
ok=false;
div.setAttribute('class', 'text-error display_block');
div.innerHTML = "Please enter a valid string.";
console.log("XXXX");
}
return ok;
}
</script>
</body>
</html>
You can add tooltip for the input field like this. Use setAttribute('title', 'some tooltip') to set the tooltip and removeAttribute('title') to remove the tooltip from the input field.
I have added input-event listener to the input field that performs validation of the input value each time you type a character and based on the result of the validation it either adds or removes the tooltip.
If you type just one character and hover over the input field, you should see the tooltip. If you type a second character it disappears (note that you need to move mouse cursor outside of the input field and then back to actually see the tooltip).
function check() {
var ok = true;
const regLast = /^[a-zA-Z]{2,20}$/;
if (!regLast.test(document.getElementById("lastName").value)) {
ok = false;
}
return ok;
}
const inp = document.querySelector('input');
inp.addEventListener('input', event => {
if (!check(inp.value)) {
inp.setAttribute('title', 'incorrect value');
} else {
inp.removeAttribute('title');
}
});
<div class="form-group">
<label for ="lastName">Last name:</label>
<input type = "text" class = "form-control" id = "lastName" placeholder = "Put your last name" name = "lastName" />
</div>
If you need something more sophisticated and more 'visible' then you can use css combined with data attributes. The logic is the same as with the previous code. Based on the result of validation you either add a data attribute to the input field or remove it.
function check() {
var ok = true;
const regLast = /^[a-zA-Z]{2,20}$/;
if (!regLast.test(document.getElementById("lastName").value)) {
ok = false;
}
return ok;
}
const inp = document.querySelector('input');
inp.addEventListener('input', event => {
if (!check(inp.value)) {
inp.parentElement.dataset.tip = 'incorrect input value';
} else {
delete inp.parentElement.dataset.tip;
}
});
[data-tip] {
position:relative;
}
[data-tip]:before {
content:'';
display:none;
content:'';
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 5px solid #1a1a1a;
position:absolute;
top:30px;
left:35px;
z-index:8;
font-size:0;
line-height:0;
width:0;
height:0;
}
[data-tip]:after {
display:none;
content:attr(data-tip);
position:absolute;
top:35px;
left:0px;
padding:5px 8px;
background:#1a1a1a;
color:#fff;
z-index:9;
font-size: 0.75em;
height:18px;
line-height:18px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
white-space:nowrap;
word-wrap:normal;
}
[data-tip]:hover:before,
[data-tip]:hover:after {
display:block;
}
<div class="form-group" >
<label for ="lastName">Last name:</label>
<input type = "text" class = "form-control" id = "lastName" placeholder = "Put your last name" name = "lastName" />
</div>
To add the tooltip on form submit instead of hover, you can use submit-event listener and execute the same code as before but you need to add event.preventDefault(); as well to prevent the form from submitting if the validation fails (and you need to change the css slightly).
When you click submit button now, you should see the tooltip if the input value is incorrect.
function check() {
var ok = true;
const regLast = /^[a-zA-Z]{2,20}$/;
if (!regLast.test(document.getElementById("lastName").value)) {
ok = false;
}
return ok;
}
const inp = document.querySelector('input');
const form = document.querySelector('form');
form.addEventListener('submit', event => {
if (!check(inp.value)) {
event.preventDefault();
inp.parentElement.dataset.tip = 'incorrect input value';
} else {
delete inp.parentElement.dataset.tip;
}
});
[data-tip] {
position:relative;
}
[data-tip]:before {
content:'';
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 5px solid #1a1a1a;
position:absolute;
top:30px;
left:35px;
z-index:8;
font-size:0;
line-height:0;
width:0;
height:0;
}
[data-tip]:after {
content:attr(data-tip);
position:absolute;
top:35px;
left:0px;
padding:5px 8px;
background:#1a1a1a;
color:#fff;
z-index:9;
font-size: 0.75em;
height:18px;
line-height:18px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
white-space:nowrap;
word-wrap:normal;
}
[data-tip]:hover:before,
[data-tip]:hover:after {
display:block;
}
<form>
<div class="form-group" >
<label for ="lastName">Last name:</label>
<input type = "text" class = "form-control" id = "lastName" placeholder = "Put your last name" name = "lastName" />
</div>
<input type="submit" value="submit" />
</form>
You can simply use the HTML5 Form Validation (If you don't want a custom tooltip).
See the code snippet below:
<form>
<p>
<label for="firstName">First name: </label>
<input type="text" id="firstName" placeholder="Put your first name" pattern="[a-zA-Z]{2,20}" required />
</p>
<p>
<label for="lastName">Last name: </label>
<input type="text" id="lastName" placeholder="Put your last name" pattern="[a-zA-Z]{2,20}" required />
</p>
<input type="submit" Value="Submit" />
</form>
Also you can use setCustomValidity function when oninvalid event occurs to to change the default message of the required field.
Example:
<form>
<p>
<label for="firstName">First name: </label>
<input type="text" id="firstName" placeholder="Put your first name" pattern="[a-zA-Z]{2,20}" oninvalid="this.setCustomValidity('Please enter a valid Name')" required />
</p>
<p>
<label for="lastName">Last name: </label>
<input type="text" id="lastName" placeholder="Put your last name" pattern="[a-zA-Z]{2,20}" required />
</p>
<input type="submit" Value="Submit" />
</form>

Html forms enter press

I have made a console using html,css,javascript
the input does not appears on enter press
the send button should b pressed
how to make it go on enter press
the code is given here please help
/* code goes below*/
<!DOCTYPE html>
<html>
<head>
<title>Konsole</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
</head>
<body>
<style>
body{
monospace
}
body{
color:#52cc29;
background-color:black;
font-family:monospace;
}
div.textarea > textarea{
height:80vh;
width:95%;
font-family:monospace;
font-size:20px;
font-weight:bold;
color:#52cc29;
background-color:black;
border:5px solid white;
}
input.command{
height:30px;
width:70%;
background-color:black;
border:3px solid white;
color:#52cc29;
font-size:15px;
text-align:left;
padding-left:4px;
font-family:monospace;
font-weight:bold;
}
h3{
font-family:monospace;
font-size:20px;
font-weight:bold;
}
input.send{
background-color:black;
color:#52cc29;
font-family:monospace;
font-weight:bold;
height:35px;
width:60px;
font-size:20px;
}
</style>
<script>
function chat(){
var time = new Date();
var hours = time.getHours();
var min = time.getMinutes();
var sec = time.getSeconds;
var write = document.getElementById("area2").value;
var read = document.getElementById("area1").value;
var newRead = "you at " +" "+hours+"h:"+min+"m"+" : " + write + "\n" + read;
document.getElementById("area1").value = newRead;
switch(write){
case "#echo.off" : document.getElementById("area1").value = "echo is off";
break;
}
}
</script>
<center>
<h3>Console</h3>
<form id="form1" >
<div class="textarea">
<textarea autocapitalize="off" spellcheck="false"
autocorrect="off" autocomplete="off" id="area1" readonly ></textarea>
</div>
</form>
<form id="form2">
<div class="input">
<input autocapitalize="off" spellcheck="false" autocorrect="off" autocomplete="off" class="command" id="area2" placeholder="type command here"></input>
<input class="send" type="button" id="button" value="send" onclick="chat();">
</div>
</form>
</center>
</body>
</html>
Try this:
<script>
window.addEventListener("keypress",handleKey);
function handleKey(e){
if(e.keyCode == 13){
chat();
}
}
</script>

How to disable Form Onsubmit function JSP

I have two radio buttons, (Yes and No) when the user choses Yes, a set of text boxes will appear and is required to have at least one entry in order to submit. If the user chose "No" he/she can submit with no entries or whatsoever. I have everything working except for the "No" part.
The validation function works inside the form, is there anyway to disable it when the chosen button is "No"?
<script type="text/javascript">
function checkEvent() {
console.log("infunc");
if(document.getElementById('events_yes').checked){
document.getElementById('if_events_yes').style.display = "block";
}
else{
document.getElementById('if_events_yes').style.display = "none";
document.getElementById('myForm').removeAttribute("onsubmit","");
}
}
</script>
<form action="ResponseDB" method="post" id="myForm">
<input name="tipid" value="<% out.println(tipid);%>" type = "hidden">
Any events to report?<br>
<input type="radio" name="events" onclick="checkEvent()" id="events_yes" value="no">Yes<br>
<input type="radio" name="events" onclick="checkEvent()" id="events_no" value="yes" checked>No<br>
<div id="if_events_yes" style="display:none">
<br><br>
Firewall:<br>
<textarea rows="5" cols="80" name="firewall"></textarea><br>
IDS/IPS:<br>
<textarea rows="5" cols="80" name="ids"></textarea><br>
Web Content Filtering/Proxy:<br>
<textarea rows="5" cols="80" name="proxy"></textarea><br>
Deep packet inspection:<br>
<textarea rows="5" cols="80" name="dpi"></textarea><br>
Network malware protection devices (FireEye, Damballa, etc.):<br>
<textarea rows="5" cols="80" name="net_malware"></textarea><br>
Anti-virus software:<br>
<textarea rows="5" cols="80" name="av" id="av"></textarea><br>
Forensics Tools:<br>
<textarea rows="5" cols="80" name="forensics"></textarea><br>
Tripwire:<br>
<textarea rows="5" cols="80" name="tripwire"></textarea><br>
Memory Dumps:<br>
<textarea rows="5" cols="80" name="memdumps"></textarea><br>
Email logs:<br>
<textarea rows="5" cols="80" name="email_logs"></textarea><br>
</div>
<input type="submit" value="Submit">
</form>
<script>
onsubmit=function() {
var t = document.getElementsByTagName("textarea"),
l = 0;
for(var i = 0; i < t.length; i++){
l = l + t[i].value.trim();
}
if (l < 1) {
alert("Please have at least one entry");
return false;
}
}
</script>
This is the portion I'm working on. Is there anyway I can disable the onsubmit function when the user choses No?
You should be able to use this example from w3schools. Their example sends to an asp page, but that doesn't matter.
I have copied the part you need here, but for more details on how or why it works visit the link above.
JavaScript Part
a JavaScript function like this but checking the state of your radio buttons:
function validateForm() {
//here just get the value(s) from your radio(s)
var x = document.forms["myForm"]["fname"].value;
//check the value
if (x == null || x == "") {
alert("Name must be filled out");
//this prevents the submit to your server
return false;
}
}
Form Part
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
It is working thanks to Kevin2 from webdeveloper.com forums....
<%#page import="com.sun.xml.internal.txw2.Document"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="db.ResponseTracker"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>MASC Response Form</title>
<style>
/* this selector could be div#nav instead of nav depending on which tag you wrapped the ul in */
#nav {
width: 100%;
float: left;
margin: 0 0 1em 0;
padding: 0;
background-color: #f2f2f2;
border-bottom: 1px solid #ccc; }
#nav ul {
list-style: none;
width: 800px;
margin: 0 auto;
padding: 0; }
#nav li {
float: left; }
#nav li a {
display: block;
padding: 8px 15px;
text-decoration: none;
font-weight: bold;
color: #069;
border-right: 1px solid #ccc; }
#nav li:first-child a {
border-left: 1px solid #ccc; }
#nav li a:hover {
color: #c00;
background-color: #fff; }
#tipid, fieldset {
display: none;
}
label {
display: block;
}
fieldset {
border: 0;
width: 50%;
}
textarea {
width: 100%;
height: 5em;
}
.active {
position: fixed;
left: 54%;
bottom: 2em;
}
</style>
<script src="nav.jsp"></script>
</head>
<body>
<div id="nav">
<ul>
<li>My Data</li>
<li>Logout</li>
</ul>
</div>
<% ResponseTracker tracker = new ResponseTracker() ;
int tipid = 0;
if(request.getParameter("tipid") != null)
{
tipid = Integer.parseInt(request.getParameter("tipid"));
}
if (tipid == 0){ response.sendRedirect("/MASC/index.jsp");}
%>
<h1> Tip report for <% out.print(tracker.getDateStringByTipId(tipid));
tracker.finalize();%></h1>
<%if(request.getParameter("failed") != null)
{
%> <br><font color=\"red\"> Login failed</font> <%
}
%>
<form action="ResponseDB" method="post">
<input name="tipid" id="tipid" value="<% out.println(tipid);%>">
Any events to report?
<label><input type="radio" name="events" onclick="checkEvent(this.value,if_events_yes,submit)" id="events_yes" value="yes">Yes</label>
<label><input type="radio" name="events" onclick="checkEvent(this.value,if_events_yes,submit)" id="events_no" value="no" checked>No</label>
<fieldset id="if_events_yes">
<label>Firewall:<br>
<textarea name="firewall"></textarea></label>
<label>IDS/IPS:<br>
<textarea name="ids"></textarea></label>
<label>Web Content Filtering/Proxy:<br>
<textarea name="proxy"></textarea></label>
<label>Deep packet inspection:<br>
<textarea name="dpi"></textarea></label>
<label>Network malware protection devices (FireEye, Damballa, etc.):<br>
<textarea name="net_malware"></textarea></label>
<label>Anti-virus software:<br>
<textarea name="av"></textarea></label>
<label>Forensics Tools:<br>
<textarea name="forensics"></textarea></label>
<label>Tripwire:<br>
<textarea name="tripwire"></textarea></label>
<label>Memory Dumps:<br>
<textarea name="memdumps"></textarea></label>
<label>Email logs:<br>
<textarea name="email_logs"></textarea></label>
</fieldset>
<input type="submit" id="submit" value="Submit">
</form>
<script>
function checkEvent(el,y,s) {
console.log("infunc");
if (el == 'yes') {
y.style.display = "block";
s.className = "active";
}
else {
y.style.display = "none";
s.className = "";
}
}
onsubmit=function() {
if (document.getElementById('events_yes').checked == true) {
var t = document.getElementsByTagName("textarea"),
l = 0;
for(var i = 0; i < t.length; i++){
l = l + t[i].value.trim();
}
if (l < 1) {
alert("Please re-enter");
return false;
}
}
}
</script>
</body>
</html>

Form and input validation

I am trying to get two inputs inside of a form tag to bring up a error message if you leave either of them blank.
I went to w3schools and tried their code but it does not work. (see below)
HTML
<form name="myForm" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
Js
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
}
I removed the action="demo_form.asp" from the code because my teacher told me to
Here is my code
HTML
<div class="loginShite">
<form name="username" onsubmit="return validateForm()" method="post">
<input type="text" name="username" placeholder="#Username" />
<input type="password" name="password" placeholder="Password" />
<br />
</form>
<div class="loginButton">
<a href="#homePage">
<input type ="button" value="login" />
</a>
</div>
</div>
Js
function validateForm() {
var x = document.forms["username"]["password"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
}
I would be greatly appreciative is somebody could either tell me what I'm doing wrong OR point me in the right direction to solve the problem.
Thank you in advance.
use type="submit" instead use of type="button",it works fine
<head>
<script>
function validateForm() {
var x = document.forms["username"]["password"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>
<div class="loginShite">
<form name="username" onsubmit="return validateForm()" method="post">
<input type="text" name="username" placeholder="#Username" />
<input type="password" name="password" placeholder="Password" /> <br
/>
<div class="loginButton"><a href="#homePage">
<input type ="submit" value="login" /></a></div> </a></div>
</form>
</div>
</body>
<!DOCTYPE html>
<html>
<head>
<script>
function validate(evt){
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
function validateForm(){
var fname = document.getElementById("fname").value;
if(fname == ""){
alert("Please Enter first name");
return false;
}
var lname = document.getElementById("lname").value;
if(lname == ""){
alert("Please Enter last name");
return false;
}
var mnumber = document.getElementById("mnumber").value;
if(mnumber == ""){
alert("Please Enter Mobile no");
return false;
}
if((mnumber.length <10)){
alert("Please Enter 10 DIGIT mobile no");
return false;
}
if((mnumber.length >10)){
alert("Please Enter 10 DIGIT mobile no");
return false;
}
var message = document.getElementById("message").value;
if(message == ""){
alert("Please Enter Message");
return false;
}
}
</script>
</head>
<body>
<form onsubmit="return validateForm()" name="form" id="form" action="" method="post">
<input type="text" name="fname" id="fname" placeholder="fname" />
<br />
<input type="text" name="fname" id="lname" placeholder="lname" />
<br />
<input type="text" name="mnumber" id="mnumber" placeholder="mnumber" onkeypress="validate(event)" />
<br />
<input type="text" name="message" id="message" placeholder="message" />
<br />
<input type="submit" value="Submit">
</form>
</html>
</body>
Here's how i've done it. You need to make sure the input type for button is "submit" else the form will not consider it as a trigger to submit. then you need to use || conditionals to test both the field conditions if they are blank or not. You can secure it more by adding the trim() method to avoid any accidental whitespaces getting accepted
Here's the HTML
<form onsubmit="return validate()" action="" class="form-group">
<div style="margin-top:2%">
<div class="col-md-4"> // bootstrap
<input type="text" id="uname" placeholder="user name"><br>
<input type="password" id="pass" placeholder="password"><br>
<input type="submit" class="btn btn-primary"><br><br>
<p id="demouname"></p>
<p id="succesuname"></p>
</div>
</div>
and here's the JS
function validate() {
var username = document.getElementById("uname");
var password = document.getElementById("pass");
if (username.value.trim() == "" || password.value.trim() == "") {
document.getElementById("demouname").style.display = "block";
document.getElementById("demouname").innerHTML = "No Empty Values Allowed";
return false;
} else {
document.getElementById("succesuname").style.display = "block";
document.getElementById("succesuname").innerHTML = "Success";
true;
}
}
and some basic css for added styling
#demouname {
display: none;
padding: 10px;
border: solid red 1px;
background-color: rgba(250, 232, 232, 0.2);
color: red;
border-radius: 5px;
-webkit-animation: shadow-drop-2-center 0.4s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
animation: shadow-drop-2-center 0.4s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
}
#succesuname {
display: none;
padding: 10px;
border: solid green 1px;
background-color: rgba(251, 252, 251, 0.521);
color: green;
border-radius: 5px;
-webkit-animation: shadow-drop-2-center 0.4s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
animation: shadow-drop-2-center 0.4s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
}
}
#-webkit-keyframes shadow-drop-2-center {
0% {
-webkit-transform: translateZ(0);
transform: translateZ(0);
box-shadow: 0 0 0 0 rgba(0, 0, 0, 0);
}
100% {
-webkit-transform: translateZ(50px);
transform: translateZ(50px);
box-shadow: 0 0 20px 0px rgba(255, 255, 255, 0.35);
}
}
#keyframes shadow-drop-2-center {
0% {
-webkit-transform: translateZ(0);
transform: translateZ(0);
box-shadow: 0 0 0 0 rgba(0, 0, 0, 0);
}
100% {
-webkit-transform: translateZ(50px);
transform: translateZ(50px);
box-shadow: 0 0 20px 0px rgba(0, 0, 0, 0.35);
}
}
Your button type should be "submit" and should be inside </form> tag.
See the form tag name and see the JavaScript how to get values from form tag.
Update
<!doctype html>
<html>
<script type="text/javascript">
function validateForm() {
var x = document.yourFormName.username.value;
var y = document.yourFormName.password.value;
if (x == "" || y == "" )
{
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="yourFormName" onsubmit="return validateForm(this.form)" method="post">
<input type="text" name="username" placeholder="#Username" />
<input type="password" name="password" placeholder="Password" />
<input type ="submit" value="login" />
</form>
</body>
</html>
Actually, all you have to do is put required at the end of the first input tag. For example:
<form>
<input type=“text” required>some text</input>
<!—-some other input—->
<input type=button>submit</input>
</form>
I believe that should work.

Replace text nodes

I'm trying to replace these two text nodes with each other. It suppose to be like a correction verification. What its suppose to do is to see if the input is correct after you focus on another input.
This is the html
<body>
<form action="" method="post" name="myform">
<fieldset>
<legend>Lab Group Form</legend>
<label for="first_name">First Name:</label>
<br/>
<input id="first_name" type="text" name="first_name_text" value="" onblur="validatefirst()" />
<br/><br/>
</fieldset>
</form>
<div class="one" id="one"/>
<div class="two" id="two"/>
</body>
function validatefirst() {
if (document.myform.first_name.value.length > 0) {
var one = document.createTextNode("Correct");
var one_container = document.getElementById("one");
} else {
var two = document.createTextNode("Incorrect.");
var two_container = document.getElementById("two");
two_container.appendChild(two);
}
}
this is the css file:
.one {
color:#000;
position:absolute;
top:400px;
}
.two{
color:#000;
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
position: absolute;
top:400px;
}
So if you can help me out that will be great. Please no jquery. Thank you
I'm not sure quite what you're trying to accomplish with the function-within-a-function. The following does something, not sure if it's what you want or not:
<html>
<head>
<style>
.one {
color:#000;
position:absolute;
top:200px;
}
.two{
color:#000;
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
position: absolute;
top:200px;
}
</style>
</head>
<body>
<form action="" method="post" name="myform">
<fieldset>
<legend>Lab Group Form</legend>
<label for="first_name">First Name:</label>
<br/>
<input id="first_name" type="text" name="first_name_text" onchange="validatefirst()" />
<br/><br/>
</fieldset>
</form>
<div class="one" id="one"/>
<div class="two" id="two"/>
</body>
<script>
function validatefirst() {
if (document.getElementById("first_name").value.length > 0) {
var one = document.createTextNode("Correct");
var one_container = document.getElementById("one");
one_container.appendChild(one);
} else {
var two = document.createTextNode("Incorrect.");
var two_container = document.getElementById("two");
two_container.appendChild(two);
}
}
</script>
</body>
</html>

Categories