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 ?
Related
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>
Hi I am new to HTML and JavaScript. I want to check the users phone number input for any letters, and print out those letters within the error message.
I'm a bit lost at the moment, can I save input as a string (as shown by the pseudo code saving input as InsertLetter). As well as put any string characters that are letters into an error message?
<form onsubmit="return isnumb()">
<label for="ph"> Enter Phone: </label>
<input type="text" id="phnumb"> <span
id="message"></span>
//InsertLetter = phnumb output
</form>
<script>
function isnumb() {
if (document.getElementById("phnumb").match =([a-z]))
{document.getElementById("message").innerHTML =
"<em> Number includes letter" + InsertLetter + "</em>";
return false;}
else return true;
It is far better to use <input type="tel"> in this situation. On that occasion user input should follow the given pattern which you can check with. Use Form Validation for the rest of the work, for example:
const phone = document.getElementById("phone");
const button = document.getElementsByTagName('button')[0];
const errorMessage = document.querySelector('p.error');
button.addEventListener('click', (e) => {
if (!phone.validity.valid) {
showError();
e.preventDefault();
}
});
phone.addEventListener('keyup', (e) => {
if (phone.validity.valid) {
errorMessage.innerHTML = '';
} else {
showError();
}
});
function showError() {
if (phone.validity.valueMissing) {
errorMessage.textContent = "Phone is required";
}
if (phone.validity.patternMismatch) {
errorMessage.textContent = "You are not supposed to use characters like this one: " + phone.value;
}
if (phone.validity.valid) {
phone.setCustomValidity("");
}
}
.error {
color: red;
}
<form>
<label for="phone">Phone Number (Format: +99 999 999 9999)</label>
<input type="tel" id="phone" name="phone" pattern="[\+]\d{2}[\s]\d{3}[\s]\d{3}[\s]\d{4}" required>
<p class="error"></p>
<button>Submit</button>
</form>
First of all i want to give u an answer of user should insert only number :`
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function submitForm() {
var phonenumber = document.forms["myForm"]["notanumber"].value;
if (isNaN(phonenumber)) {
alert("only number required");
} else {
alert("submit");
}
}
</script>
</head>
<body>
<form id="myForm">
<input type="text" id="notanumber" />
<input type="submit" onclick="submitForm()" />
</form>
</body>
</html>
-> isNaN() is an inbuilt function in js, if variable is not a number, it return true, else return false.
the simple code :
restric the user from clicking any key, Only numbers allowed.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function submit() {
alert("submited");
}
function noAlphabets(e) {
var phonenumber = document.forms["myForm"]["notanumber"].value;
var x = e.which || e.keycode;
if (x >= 48 && x <= 57) {
return submit();
} else {
alert("insert only numbers");
return false;
}
}
</script>
</head>
<body>
<form id="myForm">
<input
type="text"
id="notanumber"
onkeypress="return noAlphabets(event)"
/>
<button type="button" onclick="submit()">Submit</button>
</form>
</body>
</html>
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>
I created a little register form in HTML.
And I created a JS that pops up an alert for each of them if any of them are left blank
Now I want to combine all the alerts into a single one for example at the start a box will appear with all alerts and if you complete one if you push submit the next box will appear without the alert of the box you already completed
This is my JS Code:
function validate()
{
if( document.inrValid.Nume.value == "" )
{
alert( "Introduceti va rog numele!" );
document.inrValid.Nume.focus() ;
return false;
}
if( document.inrValid.Prenume.value == "" )
{
alert( "Introduceti va rog Prenumele!" );
document.inrValid.Prenume.focus() ;
return false;
}
if( document.inrValid.EMail.value == "" )
{
alert( "Introduceti va rog Emailul!" );
document.inrValid.EMail.focus() ;
return false;
}
if( document.inrValid.Telefon.value == "" )
{
alert( "Introduceti va rog Numarul de Telefon!" );
document.inrValid.Telefon.focus() ;
return false;
}
if( document.inrValid.parola.value == "" )
{
alert( "Introduceti va rog Parola!" );
document.inrValid.parola.focus() ;
return false;
}
return( true );
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="/cgi-bin/test.cgi" name="inrValid" onsubmit="return(validate());">
<p>Nume <input type="text" name="Nume" /></p>
<p>Prenume <input type="text" name="Prenume" /></p>
<p>EMail <input type="text" name="EMail" /></p>
<p>Telefon <input type="number" name="Telefon" /></p>
<p>Parola <input type="password" name="parola" /></p>
<p><input type="submit" onclick="clickAlert()" value="Submit" name="clickAlert" /></p>
</form>
<script src="script.js"> </script>
</body>
</html
As stated in the comment, you could use the required attribute as a small form of validation.
You could also add all of your error messages to an array, for example:
var checkForm = function () {
var foo = document.getElementById('foo');
var bar = document.getElementById('bar');
var errors = [];
if (foo.value.length === 0) {
errors.push('Foo is blank');
}
if (bar.value.length === 0) {
errors.push('Bar is blank');
}
alert(errors.join(','));
};
<form onsubmit="checkForm()">
<input id="foo" type="text" />
<input id="bar" type="text" />
<input type="submit" />
</form>
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