If else javascript error - javascript

I'm attempting to make a simple code so when you insert your name, it inserts it into the text, but if you don't insert your name it asks you to insert your name. The code seems like it should work, but it doesn't. Can anyone help me?
<body>
<h3>Please enter your name</h3>
<input type="text" id="name" value="" placeholder="Please enter your name">
<p id="dolly"></p>
<button onclick="yourName()">Enter</button>
<script>
function yourName() {
var x = document.getElementById("name").value;
if (x == "") {
document.getElementById("dolly").innerHTML = "Hello, " + x + ", My name is Dolly.";
} else {
document.getElementById("dolly").innerHTML = "Please enter your name.";
}
</script>
</body>

function yourName() {
var x = document.getElementById("name").value;
if (x.length != 0) {
document.getElementById("dolly").innerHTML = "Hello, " + x + ", My name is Dolly.";
} else {
document.getElementById("dolly").innerHTML = "Please enter your name.";
}
}

change if (x == "") to if (x != "") and close the function braces.
<body>
<h3>Please enter your name</h3>
<input type="text" id="name" value="" placeholder="Please enter your name">
<p id="dolly"></p>
<button onclick="yourName()">Enter</button>
<script>
function yourName() {
var x = document.getElementById("name").value;
if (x != "") {
document.getElementById("dolly").innerHTML = "Hello, " + x + ", My name is Dolly.";
} else {
document.getElementById("dolly").innerHTML = "Please enter your name.";
}
}
</script>
</body>

Change if(x=="") to if(x!=="" && x.length!==0) and also add a closing brace to close the function.
Full code is given below
<body>
<h3>Please enter your name</h3>
<input type="text" id="name" value="" placeholder="Please enter your name">
<p id="dolly"></p>
<button onclick="yourName()">Enter</button>
<script>
function yourName() {
var x = document.getElementById("name").value;
if (x !== "" && x.length !==0) {
document.getElementById("dolly").innerHTML = "Hello, " + x + ", My name is Dolly.";
} else {
document.getElementById("dolly").innerHTML = "Please enter your name.";
}
}
</script>
</body>

Related

InnerHTML in multiple fiields and more than one error statements

I am having trouble trying to get the form to validate using the onblur handler.
What I am trying to do is to get the first and last name field to display an error message if the field is blank, if it’s less than 5 , more than 18 characters, or it the user enters a number.
I would like to be able to do this using only one function so I do not need to do this for seperate functions.
Eg:
function ValidateName(field) {
var field = field.value;
var output = document.getElementById("fnameError");
if (field == "")
{
output = "field can’t be blank.";
return false;
}
else
{
output = "";
}
}
<form>
<input type="Text" id="Fname" onblur="ValidateName(this)">
<span id="fnameError"></span>
</form>
Your answer according to the question.
function ValidateName(field) {
var output = document.getElementById("fnameError");
if (field.value == "")
{
output.innerHTML = "field can’t be blank.";
}
else
{
output.innerHTML = "";
}
}
<form>
<input type="Text" id="Fname" onblur="ValidateName(this)">
<span id="fnameError"></span>
</form>
Your answer according to the the comment made on my answer.
function ValidateName() {
var outputF = document.getElementById("fnameError");
var outputL = document.getElementById("lnameError");
var outputB = document.getElementById("BothError");
var field1 = document.getElementById("Fname");
var field2 = document.getElementById("Lname");
if (field1.value == "" && field2.value == "")
{
outputF.innerHTML = "";
outputB.innerHTML = "No field can be left blank.";
outputL.innerHTML = "";
}
else if (field1.value !== "" && field2.value == "")
{
outputF.innerHTML = "";
outputB.innerHTML = "";
outputL.innerHTML = "field can’t be blank.";
}
else if (field1.value == "" && field2.value !== "")
{
outputF.innerHTML = "field can’t be blank.";
outputB.innerHTML = "";
outputL.innerHTML = "";
}
else {
outputF.innerHTML = "";
outputB.innerHTML = "";
outputL.innerHTML = "";
}
}
<form>
<input type="Text" id="Fname" onblur="ValidateName()">
<span id="fnameError"></span>
<br><br>
<input type="Text" id="Lname" onblur="ValidateName()">
<span id="lnameError"></span>
<br><br>
<span id="BothError"></span>
</form>
you can try this also
function validateform(){
var name=document.myform.name.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}
else if(name.length < 5){
alert("name must be atleast 8 characters long");
return false;
}
else if(name.length <18){
alert("text must be more than 18 characters");
return false;
}
}
<form name="myform" method="post" action="" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
<input type="submit" value="register">
</form>

document.getElementById is not working for a form

I have some code like this:
HTML
<div id = "inputs" style="width:300px;">
<form id = "changePwForm" name = "changePwForm" method = "POST" action = "me.php">
<input type = "password" id = "currentPw" name = "currentPw" class="loginBlank" style = "width:300px;margin-top:0px;" placeholder="Current Password"/>
<input type = "password" id = "newPw" name = "newPw" class="loginBlank" style = "width:300px;margin-top:10px;" placeholder="New password"/>
<input type = "password" id = "newPwCheck" name = "newPwCheck" class="loginBlank" style = "width:300px;margin-top:10px;" placeholder="Retype new password"/>
<input type = "button" id = "submitBtn" onclick = "checkChangeForm()" class = "loginBlank" value = "Confirm" style = "width:300px;margin-top:10px;font-size:16px;" />
</form>
</div>
JavaScript
function checkChangeForm() {
var current = document.getElementById("currentPw").value;
var newPw = document.getElementById("newPw").value;
var newPwCheck = document.getElementById("newPwCheck").value;
if (current != "" && newPw != "" && newPwCheck != "") {
if (newPw == newPwCheck) {
if (newPw.length >= 8) {
alert("OK");
document.getElementById("changePwForm").submit();
} else {
alert("Passwords must be longer than 8 characters.");
document.getElementById("currentPw").value = "";
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("newPw").focus();
}
} else {
alert("The password does not match!");
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("newPw").focus();
}
} else {
alert("No password entered");
document.getElementById("currentPw").value = "";
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("currentPw").focus();
}
}
Supposing that by the time the button is pressed, the form would have been loaded, and when the variable is created by document.getElementById("changePwForm") again, it should be existing. However, it returned NULL. Why? What is wrong here?
Fiddle: https://jsfiddle.net/fL0z59o3/#&togetherjs=FAKVrL1jG3
Inline-events expect function to be in global-scope, not under the scope of window.onload
If you want to go on with window.onload, bind event using addEventListener or Element.onEVENT_NAME
document.getElementById('submitBtn').addEventListener('click',checkChangeForm);
document.getElementById('submitBtn').addEventListener('click',checkChangeForm);
function checkChangeForm() {
var current = document.getElementById("currentPw").value;
var newPw = document.getElementById("newPw").value;
var newPwCheck = document.getElementById("newPwCheck").value;
if (current != "" && newPw != "" && newPwCheck != "") {
if (newPw == newPwCheck) {
if (newPw.length >= 8) {
alert("OK");
document.getElementById("changePwForm").submit();
} else {
alert("Passwords must be longer than 8 characters.");
document.getElementById("currentPw").value = "";
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("newPw").focus();
}
} else {
alert("The password does not match!");
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("newPw").focus();
}
} else {
alert("No password entered");
document.getElementById("currentPw").value = "";
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("currentPw").focus();
}
}
<div id="inputs" style="width:300px;">
<form id="changePwForm" name="changePwForm" method="POST" action="me.php">
<input type="password" id="currentPw" name="currentPw" class="loginBlank" style="width:300px;margin-top:0px;" placeholder="Current Password" />
<input type="password" id="newPw" name="newPw" class="loginBlank" style="width:300px;margin-top:10px;" placeholder="New password" />
<input type="password" id="newPwCheck" name="newPwCheck" class="loginBlank" style="width:300px;margin-top:10px;" placeholder="Retype new password" />
<input type="button" id="submitBtn" class="loginBlank" value="Confirm" style="width:300px;margin-top:10px;font-size:16px;" />
</form>
</div>
Without window.onload
function checkChangeForm() {
var current = document.getElementById("currentPw").value;
var newPw = document.getElementById("newPw").value;
var newPwCheck = document.getElementById("newPwCheck").value;
if (current != "" && newPw != "" && newPwCheck != "") {
if (newPw == newPwCheck) {
if (newPw.length >= 8) {
alert("OK");
document.getElementById("changePwForm").submit();
} else {
alert("Passwords must be longer than 8 characters.");
document.getElementById("currentPw").value = "";
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("newPw").focus();
}
} else {
alert("The password does not match!");
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("newPw").focus();
}
} else {
alert("No password entered");
document.getElementById("currentPw").value = "";
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("currentPw").focus();
}
}
<div id="inputs" style="width:300px;">
<form id="changePwForm" name="changePwForm" method="POST" action="me.php">
<input type="password" id="currentPw" name="currentPw" class="loginBlank" style="width:300px;margin-top:0px;" placeholder="Current Password" />
<input type="password" id="newPw" name="newPw" class="loginBlank" style="width:300px;margin-top:10px;" placeholder="New password" />
<input type="password" id="newPwCheck" name="newPwCheck" class="loginBlank" style="width:300px;margin-top:10px;" placeholder="Retype new password" />
<input type="button" id="submitBtn" onclick="checkChangeForm()" class="loginBlank" value="Confirm" style="width:300px;margin-top:10px;font-size:16px;" />
</form>
</div>
include your script just near the end of the body tag, and see if it works.
Just found the problem... I nested the <form> element in another <form> element... Removing the outer one made it work.
Please move your script just near the end of the body tag
<body>
<div id = "inputs" style="width:300px;">
<form id = "changePwForm" name = "changePwForm" method = "POST" action = "me.php">
........
</form>
<script>
function checkChangeForm() {
.....
}
</script>
</div>
</body>

validation is not done on submit button click

<script>
function ValidateEmail(){
var emailID = document.getElementById("email").value;
var email = document.getElementById("email");
var emailRegexp=/^[a-z]+\w+([\.-]?\w+)*#[a-z]+\w+([\.-]?\w+)*(\.[a-z]{2,3})+$/i;
if ((emailID==null)||(emailID=="")){
// alert("Please Enter your Email ID");
email.style.borderColor="red";
document.getElementById("err").innerHTML = "Please Enter your Email ID";
emailID.focus();
return false;
}
else
if (!emailRegexp.test(emailID)){
//alert("Please Enter valid Email ID");
email.style.borderColor="red";
document.getElementById("err").innerHTML = "Please Enter valid Email ID";
emailID.focus();
return false;
}
else
{
email.style.borderColor="#e1e1e1";
document.getElementById("err").innerHTML ="";
return true;
}
}
function validUsername()
{
var error = "";
var illegalChars = /\W/; // No special Characters allowed
var fd =document.getElementById("name");
if (fd.value == "" || fd.value == null)
{
fd.style.borderColor = 'Red';
document.getElementById("UserErr").innerHTML = " Field is left Blank.\n";
return false;
}
else if ((fd.value.length < 5) || (fd.value.length > 20)) // Number of Character entered is checked
{
fd.style.borderColor = 'Red';
document.getElementById("UserErr").innerHTML = "Username is should be in a range of 5 and 15..\n";
return false;
}
else if (illegalChars.test(fd.value)) // check for illegal characters
{
fd.style.borderColor = 'Red';
document.getElementById("UserErr").innerHTML = "Illegal Characters not allowed\n";
return false;
}
else
{
fd.style.borderColor = '#e1e1e1';
document.getElementById("UserErr").innerHTML = "";
return true;
}
}
function validPassword()
{
var error = "";
var password=document.getElementById("pass");
var passError=document.getElementById("PassErr");
var illegalChars = /[\W_]/; // Numbers and letter only
var checkPass=/\w*[a-z]+\d+\w*/i;
if (password.value == "" || password.value == null)
{
password.style.borderColor = 'Red';
passError.innerHTML = "Field Cannot be blank.\n";
return false;
}
else if ((password.value.length < 8) || (password.value.length > 20)) // Checks length of the password
{
password.style.borderColor = 'Red';
passError.innerHTML = "Length should be in Range of 8 to 20. \n";
return false;
}
else if (illegalChars.test(password.value))
{
password.style.borderColor = 'Red';
passError.innerHTML = "Illegal characters not allowed.\n";
return false;
}
else if (!checkPass.test(password.value)) // Checks for numeric value in entered password
{
password.style.borderColor = 'Red';
passError.innerHTML = "Atleast one Numeric value Required ";
return false;
}
else
{
password.style.borderColor = '#e1e1e1';
passError.innerHTML = "";
return true;
}
}
function validateOnSubmit()
{
if(ValidateEmail() && validUsername() && validPassword());
return true;
return false;
}
</script>
<form method="post" name="form">
<!--<input type="text" name="email" id="email" placeholder="Your Email" onblur="return ValidateEmail()"/><span id="err"></span></td>-->
<table align="center" width="30%" border="0">
<tr>
<td><input type="text" name="uname" id="name" placeholder="User Name" onblur="validUsername()"/><span id="UserErr" style="color:red"></span></td>
</tr>
<tr>
<td><input type="text" name="email" id="email" placeholder="Your Email" onblur="ValidateEmail()"/><span id="err"></span></td>
</tr>
<tr>
<td><input type="password" name="pass" id="pass" placeholder="Your Password" onblur="validPassword()" /><span id="PassErr" style="color:red"></span></td>
</tr>
<tr>
<td><button type="submit" onsubmit="return validateOnSubmit()" name="btn-signup">Sign Me Up</button></td>
</tr>
</table>
</form>
I have created registration form and create validation in JavaScript for input fields.
onBlur validation is done, and works fine.
But when I click on the 'Sign Me Up' button, validation is not done and data is inserted into the database. Please I need help.
submit events fire on forms, not submit buttons. Move the onsubmit attribute to the <form> start tag.
"emailID.focus(); " is wrong is in ValidateEmail() function. instead of it
"email.focus(); is right.
Now it works fine as i expected.
but there is no need of this so i removed it.

I am trying to write a function that displays the level of entry to the user in an alert box

I am currently working on trying to write a function that displays the level of entry to the user in an alert box so that the level can be confirmed or rejected, i am completely stuck, any help would be vastly appreciated, I may have got this completely wrong if so can you show me how to fix it? i am trying to make a alert box appear when i do it, yet when i try to the other validation does not work.
<html>
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg = "";
if (document.ExamEntry.name.value == "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color = "red";
result = false;
}
if (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
result = false;
}
if (document.ExamEntry.Exam_Number.value == "") {
msg += "You must enter the exam Number \n";
document.ExamEntry.subject.focus();
document.getElementById('Exam_Number').style.color = "red";
result = false;
}
if (document.ExamEntry.Exam_Number.value.length != 4) {
msg += "You must enter at least Four Numbers in the Exam Number \n";
document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number').style.color = "red";
result = false;
}
var Number = document.ExamEntry.Exam_Number.value
if (isNaN(document.ExamEntry.Exam_Number.value)) {
msg += "You must enter at least four numeric characters in the Exam Number feild \n";
document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number').style.color = "red";
result = false;
}
var checked = null;
var inputs = document.getElementsByName('Exam_Type');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
break;
}
}
if (checked == null) {
msg += "Anything for now /n";
return false;
} else {
return confirm('You have chosen ' + checked.value + ' is this correct?');
}
if (msg == "") {
return result;
} {
alert(msg)
return result;
}
}
</script>
</head>
This below is my HTML code
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="Exam_Number">Exam Number</td>
<td><input type="text" name="Exam_Number"<font size="1">(Maximum characters: 4)</font> </td>
</tr>
<tr>
<table><form action="">
<td><input type="radio" id="examtype" name="examtype" value="GCSE" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype" value="A2" /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" value="AS"/> : AS<br />
<td><input type="submit" name="Submit" value="Submit" onclick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
I hope this will work for you
JSFiddle
window.validateForm=function() {
var result = true;
var msg = "";
if (document.ExamEntry.name.value == "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color = "red";
//result = false;
}
if (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
//result = false;
}
if (document.ExamEntry.Exam_Number.value == "") {
msg += "You must enter the exam Number \n";
document.ExamEntry.subject.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
if (document.ExamEntry.Exam_Number.value.length != 4) {
msg += "You must enter at least Four Numbers in the Exam Number \n";
document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
var Number = document.ExamEntry.Exam_Number.value
if (isNaN(document.ExamEntry.Exam_Number.value)) {
msg += "You must enter at least four numeric characters in the Exam Number feild \n";
document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
var checked = null;
var inputs = document.getElementsByName('Exam_Type');
for (var i = 0; i < inputs.length; i++) {
if (!checked) {
checked = inputs[i];
}
}
if (checked == null) {
msg += "Anything for now /n";
} else {
return confirm('You have chosen ' + checked.value + ' is this correct?');
}
if (msg == "") {
return result;
} {
alert(msg)
return false;
}
}

JavaScript Alert/Confirm Error

Currently when new users register at my website, they have to fill out some forms. If their password is too short, doesn't match, they don't fill out all of the fields, or any other error, I want to alert them of it. Currently it does not alert them, so I switched to confirm. That didn't work either so I considered using showModalDiaglog. That also didn't work, I am out of Ideas. I currently have this:
HTML
<form>
First Name:<br/> <input id="firstname"/><br/>
Last Name: <br/> <input id="lastname"/><br/>
Age: <br/> <input id="age"/><br/>
Your Email:<br/> <input id="email"/><br/>
Username: <br/> <input id="username"/><br/>
Password: <br/> <input id="password"/><br/>
Confirm Password:<br/> <input type="password" id="passwordconfirm"/><br/>
<br/>
<button size=20 onClick='getRegistrationFields()'>Submit</button>
</form>​
JavaScript
function getRegistrationFields() {
var first = document.getElementById("firstname").value;
var last = document.getElementById("lastname").value;
var email = document.getElementById("email").value;
var age = document.getElementById("age").value;
var username = document.getElementById("username").value;
var password = document.getElemetnById("password").value;
var confirm = document.getElementById("passwordconfirm").value;
var empty = "";
if ((first === empty) || (last === empty) || (email === empty) || (age === empty)
|| (username === empty) || (password === empty) || (confirm === empty)) {
var message = "Not all of the fields are filled out";
prompt(message);
//showModalWindow("fields");
return false;
}
else {
age = parseInt(age);
if (password.length < 10) {
var message2 = "Password must be at least 10 characters long";
prompt(message2);
//showModalWindow("passwordlength");
return false;
}
else if (password != confirm) {
var message3 = "Passwords Do not match";
prompt(message3);
//showModalWindow("passwordmatch");
return false;
}
else if (age < 18) {
var message4 = "You must be older to register for this software.";
prompt(message4);
//showModalWindow("young");
return false;
}
else {
var message5 = "All of the fields are correct. We will be processing your request";
prompt(message5);
//showModalWindow("success");
return true;
}
}
}
function showModalWindow(fileName) {
window.showModalDialog("alerts/" + url + ".html", "", "resizable: no; height: 150; width: 350;");
}
try
html:
<button size="20" id="btn_submit">Submit</button>
js:
var btn_submit = document.getElementById("btn_submit");
btn_submit.onclick = getRegistrationFields;
Make it easy on yourself.
<input type="password" class="password" />
<input type="text" class="age" />
<script type="text/javascript">
!(function () {
var txBxs = document.querySelectorAll('input[type=textbox]'),
i = txBxs.length;
while (i--) {
tkBxs[i].onchange = textBoxCheck;
};
}());
//
function textBoxCheck() {
//
switch (this.class) {
//
case 'password':
if (this.value.length < 10)
{ alert('Password to short'); };
break;
//
case 'age':
if (+this.value < 18)
{ alert('To young kiddo!'); };
break;
};
};
</script>
There is a typo:
var password = document.getElemetnById("password").value;
You wrote getElemetnById instead of getElementById.

Categories

Resources