Javascript compare two var against known values not working? - javascript

I am trying to do a simple "login" to display a hidden div of a website by having a user input two var (userName and password) and comparing both to declared values.
<script>
function validate() {
var x = document.getElementById("userName").value
var y = document.getElementById("password").value
if (x == "Chris569x") && (y == "DM1986!"){
//Show div
}
else {
window.alert("Incorrect user name/password");
}
}
</script>
<p>DM Login
<br>
<form onSubmit="validate()">
<p>User Name:
<input type="text" id="userName">
<br>
<p>Password:
<input id="password" type="password">
<br></p>
<input name="Login" type="submit" id="Login" title="Login" value="Login" >
</form>
</div>

Your if statement
if (x == "Chris569x") && (y == "DM1986!"){
//Show div
}
Should be
if (x === "Chris569x" && y === "DM1986!"){
//Show div
}
And remember to use tripe equals instead of double.

Related

simple validation form with javascript

i have a 'div' tag included error message on the my form.
this tag displaying when button is clicked and inputs are null.
my code is working but, 'div' tag is hide speedly.
<htlm>
<head>
</head>
<body>
<div id="ShowError">
<h3>Username Or Password is incorrect.</h3>
</div>
<form id="Main" method="POST">
<input id="User" type="text" name="Name" placeholder="Enter Your Username">
<br>
<input id="Pass" type="password" name="Pass" placeholder="Enter Your Password"/>
<br>
<button id="bt">Login</button>
<button >Cancel</button>
</form>
</body>
<script src=""></script>
</html>
div#ShowError{
opacity:0.0;
}
var btn = document.getElementById("bt");
btn.addEventListener("click",func);
var Username = document.getElementById("User");
var Password = document.getElementById("Pass");
function func()
{
if(Username.value == "" || Password.value == "")
{
document.getElementById("ShowError").style.opacity = "1.0";
}
}
Clicking a submit button will submit the form.
So the JavaScript runs, the form submits, and a new page is loaded. The JavaScript hasn't run on the new page.
Prevent the default behaviour of the event if you don't want the form to submit.
function func(e)
{
if(Username.value == "" || Password.value == "")
{
e.preventDefault();
document.getElementById("ShowError").style.opacity = "1.0";
}
}
If I understand you correctly you want to slowdown the opacity change of validation error message. For example, slowly change opacity 0.0 to 1.0, right? If so, for slow change of opacity of the validation error message you have to add the css transition property using javascript to your validation error message div.
function func(event)
{
if(Username.value == "" || Password.value == "")
{
document.getElementById("ShowError").style.transition = "all 2s"
document.getElementById("ShowError").style.opacity = 1;
}
}
and also to stop reloading the page when you click login button you can include type="button" in your login button
<button type="button" id="bt">Login</button>
Working demo :
var btn = document.getElementById("bt");
btn.addEventListener("click",func);
//document.getElementById("ShowError").style.transition = "all 2s"
var Username = document.getElementById("User");
var Password = document.getElementById("Pass");
Username.addEventListener("input",func2)
Password.addEventListener("input",func2)
function func(event)
{
if(Username.value == "" || Password.value == "")
{
document.getElementById("ShowError").style.transition = "all 2s"
document.getElementById("ShowError").style.opacity = 1;
}
}
function func2(){
if(Username.value !== "" && Password.value !== ""){
document.getElementById("ShowError").style.transition = "all 2s"
document.getElementById("ShowError").style.opacity = 0;
}
}
div#ShowError{
opacity:0.0;
}
<div id="ShowError">
<h3>Username Or Password is incorrect.</h3>
</div>
<form id="Main" method="POST">
<input id="User" type="text" name="Name" placeholder="Enter Your Username">
<br>
<input id="Pass" type="password" name="Pass" placeholder="Enter Your Password"/>
<br>
<button type="button" id="bt">Login</button>
<button >Cancel</button>
</form>

How to print error message under respective input field using javascript validation in php [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
How to print error message under respective input field if left empty and error message must be removed when filled, how to proceed further i have not used javascript for validation earlier.
script code
function validateForm() {
var a = document.forms["student_reg"]["name"].value;
if (a == null || a == "") {
alert("Name must be filled out");
return false;
}
var b = document.forms["student_reg"]["email"].value;
if (b == null || b == "") {
alert("Email must be filled out");
return false;
}
var c = document.forms["student_reg"]["username"].value;
if (c == null || c == "") {
alert("Username must be filled out");
return false;
}
var d = document.forms["student_reg"]["password"].value;
if (d == null || d == "") {
alert("Password must be filled out");
return false;
}
var e = document.forms["student_reg"]["roll_no"].value;
if (e == null || e == "") {
alert("Roll no must be filled out");
return false;
}
}
html code is here
<body>
Login
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="" >
<span class="error"><p id="name_error"></p></span>
<p>EMAIL:</p>
<input type="text" name="email" value="" >
<span class="error"><p id="email_error"></p></span>
<p>USERNAME:</p>
<input type="text" name="username" value="" >
<span class="error"><p id="username_error"></p></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="" >
<span class="error"><p id="password_error"></p></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="" >
<span class="error"><p id="roll_no_error"></p></span>
<br/>
<br/>
<br/>
<input type="submit" name="submit" value="submit">
</form>
</body>
You can try this code:
It will check errors and returns at last after displaying all error messages if any.
function validateForm() {
var error = 0;
var a = document.forms["student_reg"]["name"].value;
document.getElementById('name_error').innerHTML = '';
if (a == null || a == "") {
// alert("Name must be filled out");
error++;
document.getElementById('name_error').innerHTML = 'Name must be filled out';
}
var b = document.forms["student_reg"]["email"].value;
document.getElementById('email_error').innerHTML = '';
if (b == null || b == "") {
// alert("Email must be filled out");
error++;
document.getElementById('email_error').innerHTML = 'Email must be filled out';
}
var c = document.forms["student_reg"]["username"].value;
document.getElementById('username_error').innerHTML = '';
if (c == null || c == "") {
// alert("Username must be filled out");
error++;
document.getElementById('username_error').innerHTML = 'Username must be filled out';
}
var d = document.forms["student_reg"]["password"].value;
document.getElementById('password_error').innerHTML = '';
if (d == null || d == "") {
// alert("Password must be filled out");
error++;
document.getElementById('password_error').innerHTML = 'Password must be filled out';
}
var e = document.forms["student_reg"]["roll_no"].value;
document.getElementById('roll_no_error').innerHTML = '';
if (e == null || e == "") {
// alert("Roll no must be filled out");
error++;
document.getElementById('roll_no_error').innerHTML = 'Roll no must be filled out';
}
if(error>0) {
return false;
}
return true;
}
Keep all the name attributes in array and validate in loop. As your ID is related to name attribute, concatenate the name with _error to get the ID of the error placeholder.
function validateForm() {
var names = ['name', 'email', 'username', 'password', 'roll_no'];
var errorCount = 0;
names.forEach(function(el) {
var val = document.forms["student_reg"][el].value;
if (val == null || val == "") {
document.getElementById(el + '_error').textContent = el.toUpperCase().replace('_', ' ') + " must be filled out";
++errorCount;
}
});
if (errorCount) return false;
}
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="">
<span class="error"><p id="name_error"></p></span>
<p>EMAIL:</p>
<input type="text" name="email" value="">
<span class="error"><p id="email_error"></p></span>
<p>USERNAME:</p>
<input type="text" name="username" value="">
<span class="error"><p id="username_error"></p></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="">
<span class="error"><p id="password_error"></p></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="">
<span class="error"><p id="roll_no_error"></p></span>
<br/>
<br/>
<br/>
<input type="submit" name="submit" value="submit">
</form>
You can iterate through all elements of the form student_reg to validate email and required and print error message under respective input field if no value was set:
const validateForm = () => {
const form = document.forms['student_reg'],
inputs = [...form.getElementsByTagName('input')],
errors = [...form.getElementsByClassName('error')],
regex = /\S+#\S+\.\S+/,
setErrorMsg = (str, msg) => `${str.replace('_', ' ')} ${msg}`
let countErrors = 0
inputs.forEach((input, index) => {
// clear all errors
(errors[index] || '').innerHTML = ''
// validate email
if (input.name === 'email' && !regex.test(input.value)) {
errors[index].innerText = setErrorMsg(input.name, 'should be valid')
countErrors++
}
// validate required
if (!input.value) {
errors[index].innerText = setErrorMsg(input.name, 'field is required')
countErrors++
}
})
return countErrors === 0
}
p {
font-size: 13px;
margin: 4px 0 0;
}
.error {
font-size: 12px;
padding: 6px 0 4px;
color: red;
display: block
}
.error:first-letter {
text-transform: uppercase
}
button {
margin-top: 8px;
font-size: 16px;
}
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="">
<span class="error"></span>
<p>EMAIL:</p>
<input type="text" name="email" value="">
<span class="error"></span>
<p>USERNAME:</p>
<input type="text" name="username" value="">
<span class="error"></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="">
<span class="error"></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="">
<span class="error"></span>
<button>Submit</button>
</form>
simple form It hold the Span for the Error msg.The span Id is very important here.you need to make color for errors using css
<form id="loginform" name="loginform" action="" method="post">
<label>Name</label>
<input type="text" name="username" />
<p></p>
<span id="usernameError"></span>
<p></p>
<label>Pwd</label>
<input type="password" name="password" />
<p></p>
<span id="passwordError"></span>
<p></p>
<input type="submit" value="Submit" />
</form>
script
<script type="application/javascript">
window.onload = function(){
function handleinput(){
if(document.loginform.username.value == ""){
document.getElementById("usernameError").innerHTML = "You must enter a username";
return false;
}
if(document.loginform.password.value == ""){
document.getElementById("passwordError").innerHTML = "You must enter a password";
return false;
}
}
document.getElementById("loginform").onsubmit = handleinput;
}
</script>

JavaScript not working for button inside form

I'm trying to use JavaScript and PHP together for the first time.
PHP, as far as I know, requires the submit button to be inside the form tags. However, for some reason, JavaScript ONLY works if the submit button is outside the form. If I move the submit button inside the form tags I get this error:
"index.html:94 Uncaught TypeError: submitBtn is not a function".
Is there a way to either 1) get PHP to work with the button OUTSIDE the form? OR 2) get JavaScript to work with the button INSIDE the form?
HTML:
<form>
<div class="form" id="form">
<label for="name">Name</label><br>
<input type="text" name="username" id="name"><br>
<label for="email">Email</label><br>
<input type="text" name="username" id="email"><br>
<label for="comment">Reason for contacting</label><br>
<textarea rows="3" id="comment" name="comment"></textarea>
<br>
</div>
<button type="button" name="submitButton" id="submitBtn" onclick="submitBtn()">SEND</button>
</form>
JavaScript:
function submitBtn() {
var name = document.getElementById('name');
var email = document.getElementById('email').value;
var comment = document.getElementById('comment');
if(name.value.length > 1 && name.value.length < 50) {
if(email.length > 5 && email.length < 50 && email.indexOf('#') >= 0 && email.indexOf('.') >= 0 && !(email.indexOf(' ') >= 0)) {
if(comment.value.length > 9 && comment.value.length < 500) {
alert("Thanks");
} else {
alert("Message must be between 10 and 500 characters");
}
} else {
alert("Not a valid email");
}
} else {
alert("Name must be longer than three characters");
}
};
Change the button's id to submitBtnId
elements's ID and function's name cannot be same, because they are all identifiers.
<button type="button" name="submitButton" id="submitBtnId" onclick="submitBtn()">SEND</button>
You must change the function name or the button id because both are same.

How to submit a form from script

I have a simple form:
<form id="form" method="post" action="email.php">
<input id="name" name="name" type="text" placeholder="Name" />
<input name="email" id="email" type="text" placeholder="Email" />
<textarea name="text" id="msg" placeholder="Comment"></textarea>
<input type="button" value="SUBMIT" id="submit" onclick="empty()"/>
</form>
and an empty() function for checking if all inputs are there:
function empty(){
var x; var y; var z;
x = document.getElementById("name").value;
y = document.getElementById("email").value;
z = document.getElementById("msg").value;
if (x == "" || y == "" || z == "") {
document.getElementById("errors").innerHTML = "All inputs must be present before submitting.";
return false;
}else{
document.form.submit(); /*this doesn't work*/
}
}
But I can't seem to get the form to submit...
The problem is with the button type. Try this:
<script>
function empty() {
var x;
var y;
var z;
x = document.getElementById("name").value;
y = document.getElementById("email").value;
z = document.getElementById("msg").value;
if (x == "" || y == "" || z == "") {
document.getElementById("errors").innerHTML = "All inputs must be present before submitting.";
return false; // the only reason this worked previously is that the input type was wrong so the form didn't submit
} else {
return true; // return true instead of trying to submit the form with js
}
}
</script>
<form id="form" method="post" action="email.php">
<input id="name" name="name" type="text" placeholder="Name" />
<input name="email" id="email" type="text" placeholder="Email" />
<textarea name="text" id="msg" placeholder="Comment"></textarea>
<input type="submit" value="SUBMIT" id="submit" onclick="return empty();" />
<!-- change the button type to submit and return the value from the empty function (false will prevent the default action of the button - stop the form submitting, true will allow the form to submit) -->
</form>
<div id="errors"></div>
Noticed this doesn't work as a snippet so this is it working in a fiddle
You need to define name of the form.After define this form can be submit using javascript.
To check example you can follow this example-
<form name="myform" action="handle-data.php">
Search: <input type='text' name='query' />
Search
</form>
<script type="text/javascript">
function submitform()
{
document.myform.submit();
}
</script>

Single click to submit form

I'm having an issue when trying to submit my form. I have made a workaround so that the input gets sent to parse.com by using a hidden button which is visible until all fields are filled in, then this button is hidden and the real submit button is enabled. The problem is that I want to be able to submit the form directly by clicking the submit button without having to click the button twice. I have the following HTML:
<form id="vcardForm" method="post" >
<p>
<input type="text" id="name" name="name" required />
</p>
<p>
<input type="text" id="vorname" name="vorname" required />
</p>
<p>
<input type="text" id="email1" name="email1" required />
<label id="atteken" >#</label>
<input type="text" id="email2" name="email2 " required />
<textarea id="fullemail" name="fullemail"></textarea>
<p>
<input type="text" id="telefon" name="telefon" onclick="getFullemail()" />
</p>
<p>
<input type="text" id="firma" name="firma" required />
</p>
<p>
<input type="submit" id="submitBtn" onclick="functions()" value=" " disabled>
<button type="button" id="submitKnop" onclick="validateForm()" ></button>
Javascript:
<script type="text/javascript">
function getFullemail() {
document.getElementById('fullemail').value =
document.getElementById('email1').value + '#' +
document.getElementById('email2').value;
}
</script>
<script>
function validateForm() {
var name = document.getElementById('name').value;
var vorname = document.getElementById('vorname').value;
var email = document.getElementById('fullemail').value;
var firma = document.getElementById('firma').value;
var telefon = document.getElementById('telefon').value;
if(name == '' || vorname == '' || email == '' || firma == '' || telefon == '' ) {
alert('Bitte alle Felder ausfüllen. Danke.');
e.preventDefault();
}else {
document.getElementById('submitKnop').style.visibility = 'hidden';
document.getElementById('submitBtn').disabled = false;
}
}
</script>
<script>
function functions() {
sendTheMail();
}
</script>
Parse.com script
$(document).ready(function() {
var parseAPPID = "bla";
var parseJSID = "bla";
Parse.initialize(parseAPPID, parseJSID);
var VcardObject = Parse.Object.extend("VcardObject");
$("#vcardForm").on("submit", function(e) {
e.preventDefault();
console.log("Handling the submit");
//add error handling here
//gather the form data
var data = {};
data.name = $("#name").val();
data.vorname = $("#vorname").val();
data.fullemail = $("#fullemail").val();
data.telefon = $("#telefon").val();
data.firma = $("#firma").val();
var vcard = new VcardObject();
vcard.save(data, {
success:function() {
openPage('danke');
console.log("Success");
},
error:function(e) {
console.dir(e);
}
});
});
});
If i understand you correctly, you'd like to click button after form is filed and if all fields are valid the form should be send. If so you need to do following changes:
1) remove from html
<input type="submit" id="submitBtn" onclick="functions()" value=" " disabled>
2) change your validateForm - replace this lines
document.getElementById('submitKnop').style.visibility = 'hidden';
document.getElementById('submitBtn').disabled = false;
with
functions()
It will spare your from using two buttons.When submit button is clicked check if all the fields are filled in or not.Use && operator instead of || operator.Because you want all the fields to be filled
if(name != '' && vorname != '' && email != '' && firma != '' && telefon != '' )
If all fields are filled it will alert a message which will tell you that your form is submitted.Otherwise it will alert you to fill all the fields
function validateForm() {
var name = document.getElementById('name').value;
var vorname = document.getElementById('vorname').value;
var email = document.getElementById('fullemail').value;
var firma = document.getElementById('firma').value;
var telefon = document.getElementById('telefon').value;
if(name != '' && vorname != '' && email != '' && firma != '' && telefon != '' ) {
alert('form is sumbitted.');
e.preventDefault();
}else {
alert('fill all fields !!');
}
}
<form id="vcardForm" method="post" >
<p>
<input type="text" id="name" name="name" required />
</p>
<p>
<input type="text" id="vorname" name="vorname" required />
</p>
<p>
<input type="text" id="email1" name="email1" required />
<label id="atteken" >#</label>
<input type="text" id="email2" name="email2 " required />
<textarea id="fullemail" name="fullemail"></textarea>
<p>
<input type="text" id="telefon" name="telefon" onclick="getFullemail()" />
</p>
<p>
<input type="text" id="firma" name="firma" required />
</p>
<p>
<input type="submit" id="submitBtn" onclick="validateForm()" value=" submit " >
modify validateForm
function validateForm() {
var name = document.getElementById('name').value;
var vorname = document.getElementById('vorname').value;
var email = document.getElementById('fullemail').value;
var firma = document.getElementById('firma').value;
var telefon = document.getElementById('telefon').value;
if(name == '' || vorname == '' || email == '' || firma == '' || telefon == '' ) {
alert('Bitte alle Felder ausfüllen. Danke.');
return false
}
return true
}
and replace
console.log("Handling the submit");
//add error handling here
//gather the form data
with
if(!validateForm()) return
sendTheMail(...al your params here)
and the last step replace in your html
<input type="submit" id="submitBtn" onclick="functions()" value=" " disabled>
<button type="button" id="submitKnop" onclick="validateForm()" ></button>
with
<input type="submit" id="submitBtn" value=" ">

Categories

Resources