used for validating the strings inputted.
no if conditions works in the js code but the else if one,asking for help.
html code:
<div>
<h2 class="title">login</h2>
<p>usernamehere:</p>
<input type="text" name="username" id="username" placeholder="login">
<p>passwordhere:</p>
<input type="password" name="userpassword" id="userpswd" placeholder="password">
<button id="login">login</button>
</div>
<script src="jquery-3.6.0.min.js" type="text/javascript"></script>
<script src="main.js" type="text/javascript"></script>
js code:
var userenter = $("#username").val()
var pswdenter = $("#userpswd").val()
$("#login").click(function(){
if(userenter == "letsstart" && pswdenter == "start"){
alert("pass");
}
else if(userenter == "" || pswdenter == ""){
alert("enter please")
}
else{
alert("invalid")
}
});
You should read the .val of username and password inside the click handler instead of global . Otherwise it will have the document initial load value of the input . That's why each time you got empty input
$("#login").click(function() {
var userenter = $("#username").val() //
var pswdenter = $("#userpswd").val() //
console.log(userenter,pswdenter)
if (userenter == "letsstart" && pswdenter == "start") {
alert("pass");
} else if (userenter == "" || pswdenter == "") {
alert("enter please")
} else {
alert("invalid")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<h2 class="title">login</h2>
<p>usernamehere:</p>
<input type="text" name="username" id="username" placeholder="login">
<p>passwordhere:</p>
<input type="password" name="userpassword" id="userpswd" placeholder="password">
<button id="login">login</button>
</div>
You are retrieving the values of username and userpswd once and then using it in the click handler. So your if statement is always looking at the values from the first time they were set (probably on page load).
You should move the value retrieval code inside you click handler.
$("#login").click(function(){
var userenter = $("#username").val()
var pswdenter = $("#userpswd").val()
...
});
You have to get the values of #username and #userpswd everytime you click on the "login" button. Otherwise, userenter and pswdenter will be empty when you will check if credentials are valid or not, because when you define them #username and #userpswd inputs are empty. I don't know if it's well explained, but here is the code :
$("#login").click(function(){
var userenter = $("#username").val()
var pswdenter = $("#userpswd").val()
if(userenter == "letsstart" && pswdenter == "start"){
alert("pass");
}
else if(userenter == "" || pswdenter == ""){
alert("enter please")
}
else{
alert("invalid")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<h2 class="title">login</h2>
<p>usernamehere:</p>
<input type="text" name="username" id="username" placeholder="login">
<p>passwordhere:</p>
<input type="password" name="userpassword" id="userpswd" placeholder="password">
<button id="login">login</button>
</div>
<script src="jquery-3.6.0.min.js" type="text/javascript"></script>
<script src="main.js" type="text/javascript"></script>
Related
I'm trying to use Javascript to validate that three fields all have contents in them before proceeding to submit the form.
HTML Code:
<form name="form">
<input id="OldPassword" type="password">
<input id="NewPassword" type="password">
<input id="ConfirmNewPassword" type="password">
<div id="okButtonContainer">
<span>Submit</span>
<a href="#" onclick="validateForm()" id="submitButton">
</a>
</div>
</form>
Javascript Code:
<script>
function submitJSForm()
{
document.getElementById('form').submit();
}
function validateForm()
{
var a = document.getElementById("OldPassword").value;
var b = document.getElementById("NewPassword").value;
var c = document.getElementById("ConfirmNewPassword").value;
alert("Got to here");
if (a == null || a == "" || b == null || b == "" || c == null || c == "")
{
alert("Please Fill All Required Field");
// do nothing
}
else
{
alert("Submitting...")
submitJSForm();
}
alert("Got to end function");
}
</script>
All IDs match and haven't got any spelling mistakes.
Whenever I enter contents into all three fields, the if statement runs the alert "Please Fill All Required Field" which it shouldn't. What am I doing wrong?
You could use a function called checkValidity()
By adding the required tag to each input, the following will let you know if everything is filled in inside your form
var form = document.getElementById(‘MyForm’);
var isValidForm = form.checkValidity();
it works with ID, try this
function submitJSForm()
{
document.getElementById('form').submit();
}
function validateForm()
{
var a = document.getElementById("OldPassword").value;
var b = document.getElementById("NewPassword").value;
var c = document.getElementById("ConfirmNewPassword").value;
alert("Got to here");
if (a == null || a == "" || b == null || b == "" || c == null || c == "")
{
alert("Please Fill All Required Field");
// do nothing
}
else
{
alert("Submitting...")
submitJSForm();
}
alert("Got to end function");
}
<form name="form" id="form">
<input id="OldPassword" type="password">
<input id="NewPassword" type="password">
<input id="ConfirmNewPassword" type="password">
<div id="okButtonContainer">
<a href="#" onclick="validateForm()" id="submitButton">
<span>Submit</span>
</a>
</div>
</form>
I tried to reproduce the error you got but the validation passed
correctly here is my code based on your script.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form id="form">
<input type="password" id="OldPassword" />
<input type="password" id="NewPassword" />
<input type="password" id="ConfirmNewPassword" />
<input onclick="validateForm()" value="Submit" />
</form>
<script>
function submitJSForm() {
document.getElementById('form').submit();
alert("Submitting...");
}
function validateForm() {
var a = document.getElementById("OldPassword").value;
var b = document.getElementById("NewPassword").value;
var c = document.getElementById("ConfirmNewPassword").value;
if (a == null || a == "" || b == null || b == "" || c == null || c == "") {
alert("Please Fill All Required Field");
// do nothing
}
else {
submitJSForm();
}
}
</script>
</body>
</html>
Can you please post the HTML part of your answer ?
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>
<!DOCTYPE html>
<html>
<body>
<div class="needContent">
<label for="Password">Password</label>
<span class="red-star">∗</span>
<input type="password" name="Password" id="Password" required="required" onkeyup="starShow()" pattern="^(?=.*\[a-z\])(?=.*\[A-Z\])(?=.*\d)\[a-zA-Z\d\]{8,}$" onchange="check()">
</div>
<div class="needContent">
<label for="Retype_Password">Retype Password</label>
<span class="red-star">∗</span>
<input type="password" name="Retype_Password" id="Retype_Password" pattern="^(?=.*\[a-z\])(?=.*\[A-Z\])(?=.*\d)\[a-zA-Z\d\]{8,}$" required="required" onkeyup="starShow()" onchange="check()">
<p id="status"></p>
<div id="phoneNumber" class="needContent">
<label for="Phone_Number" >Phone Number</label>
<span class="red-star">∗</span>
<input type="tel" name="Phone_Number" id="Phone_Number"
required="required" onchange="Error()" placeholder="999-999-9999"
onkeyup="starShow()" >
<p id="showEorror"></p>
</div>
</div>
<script>
function Error() {
var phn = document.getElementById("Phone_Number").value;
if(phn[3]!="-" && phn[7] != "-" ) {
document.getElementById("showEorror").innerHTML="<span>X</span> The area code of phone number 999-999-9999 can't be all zeros.";
}else if(phn[0] == 0 || phn[1] == 0 && phn[2] == 0){
document.getElementById("showEorror").innerHTML="<span>X</span> The area code of phone number 999-999-9999 can't be all zeros.";
} else {
document.getElementById("showEorrr").style.display = "none";
}
}
function check() {
var pass1 = document.getElementById("Password").value;
var pass2 = document.getElementById("Retype_Password").value;
if (pass1 != "" && pass2 != "") {
if (pass1 != pass2) {
document.getElementById("status").innerHTML = "<span>X</span> Doesn't Match.";
}
}
}
</script>
</body>
</html>
So I am working on my school project and I am trying to display the error "Doesn't Match" same as the one for the phone but I don't know what I am doing wrong. I have attached a screen shot of my output.
You're not resetting the #status text after the password gets properly entered. Try this instead:
if (pass1 != "" && pass2 != "") {
if (pass1 != pass2) {
document.getElementById("status").innerHTML = "<span>X</span> Doesn't Match.";
} else document.getElementById("status").textContent = 'ok';
}
For the phone section, you have a typo or two: "showEorror" vs "showEorrr", which means that, again, the error text does not go away. I recommend using showError or showPhoneError instead.
The phone number and the email must be valid.
This is a basic popup contact form without the phone number validation. I would like to validate the phone number. I heard about regex but i´m not sure how to implement in the code.
Since i don´t understand javascrip yet i hope you can help me.
<form action="#" method="post" id="form">
<h2>Contact Us</h2><hr/>
<input type="text" name="company" id="company" placeholder="Company"/>
<input type="text" name="name" id="name" placeholder="Name"/>
<input type="text" name="email" id="email" placeholder="Email"/>
<input type="text" name="phone" id="email" placeholder="Phone"/>
<a id="submit" href="javascript: check_empty()">Send</a>
</form>
function check_empty(){
if(document.getElementById('company').value == ""
|| document.getElementById('name').value == ""
||document.getElementById('email').value == ""
||document.getElementById('phone').value == "" ){
alert ("Please, fill the fields!");
}
else {
document.getElementById('form').submit();
}
}
//function to display Popup
function div_show(){
document.getElementById('abc').style.display = "block";
}
//function to check target element
function check(e){
var target = (e && e.target) || (event && event.srcElement);
var obj = document.getElementById('abc');
var obj2 = document.getElementById('popup');
checkParent(target)?obj.style.display='none':null;
target==obj2?obj.style.display='block':null;
}
//function to check parent node and return result accordingly
function checkParent(t){
while(t.parentNode){
if(t==document.getElementById('abc'))
{
return false
}
else if(t==document.getElementById('close'))
{
return true
}
t=t.parentNode
}
return true
}
I am trying to take a username and password as input and if the entered username and password are admin admin I want to forward them to a new php file. I dont understand where I am going wrong. Any help. Thank you in advance
<html>
<head>
<script type="text/javascript">
function validate()
{
window.alert("called");
var user=document.getelementbyId(log).value;
var pass=document.getelementbyId(password).value;
window.alert("stored");
if((user=="admin")&&(pass="admin"))
{
window.alert("logging");
window.location.href='edusculpt_admin.php';
}
else
window.alert("Username or Password Incorrect");
}
</script>
</head>
<body>
<h3>Admin Login</h3>
<form method="post">
<p>
Login ID: <input type="text" id="log" value=""
placeholder="Username or Email">
</p>
<p>
Password: <input type="password" id="password" value=""
placeholder="Password">
</p>
<input type="submit" value="Login" onclick="validate()">
</form>
</body>
</html>
Javascript is case sensitive, getelementbyId should be getElementById and id's needs to be wrapped in quotes.
<script type="text/javascript">
function validate()
{
window.alert("called");
var user=document.getElementById('log').value;
var pass=document.getElementById('password').value;
window.alert("stored");
if((user=="admin")&&(pass=="admin"))
{
window.alert("logging");
window.location.href='edusculpt_admin.php';
}
else
window.alert("Username or Password Incorrect");
}
</script>
Also Note, You have submit button in your form .. which is not handled in validate function, either you can make <input type="button" ... or handle event in validate method.
getelementbyId should be getElementById & enclose the ID name by quote
var user=document.getElementById("log").value;
var pass=document.getElementById("password").value;
And compare by == instead of =
if((user=="admin")&&(pass=="admin"))
^^^
change onclick="validate()" to onclick="return validate();".
this way, when validate returns false, the form won't click. you'd also have to change the validate func to return false when the form doesn't validate, the resulting code would be:
<html>
<head>
<title>
User Validation : 2nd Program
</title>
<script type="text/javascript">
function validate()
{
alert(form.username.value)
alert(document.getelementbyId(username).value);
alert(form.password.value)
if(form.username.value == "sample" && form.password.value =="password")
{
alert("User Validated ");
return true;
}
else
{
alert("Incorrect Username or Password" );
return false;
}
}
</script>
</head>
<h3>Admin Login</h3>
<form method="post">
<p>
Login ID: <input type="text" id="log" value=""
placeholder="Username or Email">
</p>
<p>
Password: <input type="password" id="password" value=""
placeholder="Password">
</p>
<input type="submit" value="Login" onclick="validate()">
</form>
</body>
</text>
</body>
try this one
<script type="text/javascript">
function validate()
{
alert(form.username.value)
alert(document.getelementbyId(username).value);
alert(form.password.value)
if(form.username.value == "sample" && form.password.value =="password")
{
alert("User Validated ");
return true;
}
else
{
alert("Incorrect Username or Password" );
return false;
}
}
</script>
Update: continue and break illustrated.
while(true) {
// :loopStart
var randomNumber = Math.random();
if (randomNumber < .5) {
continue; //skips the rest of the code and goes back to :loopStart
}
if (randomNumber >= .6) {
break; //exits the while loop (resumes execution at :loopEnd)
}
alert('value is between .5 and .6');
}
// :loopEnd