I'm trying to manually validate a form in HTML/CSS/JS. At the very basic level, I want to ensure that the user cannot input blank values for first name and last name. The problem is that whenever I try to change or update the inputs to what the user has written, it doesn't save. Everything remains "null". It's also extremely frustrating that in my JS code when I'm trying to use an IF statement to check if the first name has no value or is null, I get an immediate error message that "first" is null, because its null no matter what, if you input something or not, but it doesn't even complete it's job. I'm using the if statement to CHECK if its null, not for it to do something with it, so why is it having an issue simply following the code below it if the condition is true? I've sat on this for like an hour and its becoming unbearable. I'm new to JS and Im really not getting how something as simple as IF statements isn't working for me.
HTML form:
<form action="" method="get" id="my-form">
<h1>Contact Us</h1>
<div class="txtb">
<label>First Name :</label>
<input type="text" id = "firstname" placeholder="Enter Your First Name">
</div>
<div class="txtb">
<label>Last Name :</label>
<input type="text" id = "lastname" placeholder="Enter Your Last Name">
</div>
<div class="txtb">
<label>Email :</label>
<input type="email" id = "email" placeholder="Enter Your Email" required>
</div>
<div class="txtb">
<label>Date Visited :</label>
<input type="date" id = "date" required>
</div>
<div class="txtb">
<label>What did you think of it when you visited? :</label>
<textarea id = "msg" required></textarea>
</div>
<button type='submit'>Submit</button>
<!--onclick = form.submit()-->
</form>
</div>
<div id="error"></div>
New JS:
let first = document.getElementById("firstname").value;
let last = document.getElementById("lastname").value;
let email = document.getElementById("email").value;
let msg = document.getElementById("msg").value;
let date = document.getElementById("date").value;
let form = document.getElementById("my-form");
let errorEl= document.getElementById("error");
function formChanged() {
first = document.getElementById("firstname");
last = document.getElementById("lastname");
email = document.getElementById("email");
msg = document.getElementById("msg");
date = document.getElementById("date");
console.log(first,last,email,msg,date,form)
}
form.addEventListener('submit', (e) => {
let messages = []
console.log(first, last)
if (first === '' || first == null){
messages.push('First name is required')
}
if (last === '' || last == null){
messages.push('Last name is required')
}
if (messages.length>0){
e.preventDefault()
errorEl.innerText = messages.join(', ')
}
console.log(first, last)
})
//window.alert(messages)
If anyone knows a better way to do this manually also, it would be greatly appreciated if you could share it. At this point, everything works except the messages array remains the same, so I'm going to add something to remove the messages if first doesn't == null or ''
Edit :
You are doing first = document.getElementById("firstname").value; so it get by ID but you don't have any id.
For example, change
<input type="text" name = "firstname" placeholder="Enter Your First Name">
to
<input type="text" id="firstname" name="firstname" placeholder="Enter Your First Name">
Notice the id="firstname".
Original Answer :
Your function
function formChanged() {
first = document.getElementById("firstname").value;
last = document.getElementById("lastname").value;
email = document.getElementById("email").value;
msg = document.getElementById("msg").value;
date = document.getElementById("date").value;
console.log(first,last,email,msg,date,form)
}
Is setting first to document.getElementById("firstname").value; while you first initialized it to
let first = document.getElementById("firstname");.
Notice, that in your function you set it to the input's .value, not the input itself.
So if (first.value === '' || first.value == null) won't work because first is already equal to .value thus you are in fact doing document.getElementById("firstname").value.value which is undefined !
Try either :
to change formChanged variable initialisation to document.getElementById("firstname")
OR
change the if to if (first == '' || first== null)
Adding on to what Sorikairo said:
From this answer, add a return value to your onsubmit instead of preventDefault:
if (messages.length>0){
// e.preventDefault()
return false;
errorEl.innerText = messages.join(', ')
}
return true;
SOLVED:
If you run into this problem, check all of your .value lines, because doubling them up or not having enough was the main problem here. Everything was being checked against the wrong things. I also recommend console.log() ing everything you do like I did just for variable tracking.
Final JS:
let first = document.getElementById("firstname").value;
let last = document.getElementById("lastname").value;
let email = document.getElementById("email").value;
let msg = document.getElementById("msg").value;
let date = document.getElementById("date").value;
let form = document.getElementById("my-form");
let errorEl= document.getElementById("error");
function formChanged() {
first = document.getElementById("firstname").value;
last = document.getElementById("lastname").value;
email = document.getElementById("email").value;
msg = document.getElementById("msg").value;
date = document.getElementById("date").value;
form= document.getElementById("my-form");
errorEl = document.getElementById("error");
console.log(first,last,email,msg,date,form)
}
form.addEventListener('submit', (e) => {
formChanged()
errorEl.innerText = '';
var messages = []
if (first === '' || first == null){
messages.push('First name is required')
}
if (last === '' || last == null){
messages.push('Last name is required')
}
if (messages.length>0){
e.preventDefault()
errorEl.innerText = messages.join(', ')
}
console.log(first, last)
console.log(messages)
})
//window.alert(messages)
Final HTML:
<form action="" method="get" id="my-form">
<h1>Contact Us</h1>
<div class="txtb">
<label>First Name :</label>
<input type="text" id = "firstname" placeholder="Enter Your First Name">
</div>
<div class="txtb">
<label>Last Name :</label>
<input type="text" id = "lastname" placeholder="Enter Your Last Name">
</div>
<div class="txtb">
<label>Email :</label>
<input type="email" id = "email" placeholder="Enter Your Email" required>
</div>
<div class="txtb">
<label>Date Visited :</label>
<input type="date" id = "date" required>
</div>
<div class="txtb">
<label>What did you think of it when you visited? :</label>
<textarea id = "msg" required></textarea>
</div>
<button type='submit'>Submit</button>
<!--onclick = form.submit()-->
</form>
</div>
<div id="error"></div>
Related
I have a form in HTML and I want to display the form text input data on the same page but before pressing the submit button.
Mean, When Users put the data in the form it must display below the form on same page.
It's mean that I want to show all data before submitting the form.
I know this code will not work as i want
var strText = document.getElementById("textone");
document.write(strText.value);
var strText1 = document.getElementById("textTWO");
document.write(strText1.value);
}
This is how I would do it by directly manipulating the DOM:
const input = document.getElementById('textInput');
const textElement = document.getElementById('displayText');
function updateValue(e) {
textElement.textContent = e.target.value;
}
input.addEventListener('input', updateValue);
<input type="text" id="textInput">
<p>value from input:</p>
<div id="displayText"></div>
There are also javascript libraries like VueJS and ReactJS that can help you do this more easily and efficiently.
This is an example of something like what you would want to do in VueJS: https://v2.vuejs.org/v2/examples/index.html
I've prepared an example of general functioning, I hope you like it. It may not be exactly what you want, but if it is, please tell me.
const myForm = document.getElementById("myForm");
const nameInput = document.getElementById("nameInput");
const emailInput = document.getElementById("emailInput");
const nameOutput = document.getElementById("nameOutput");
const emailOutput = document.getElementById("emailOutput");
let nameSpan = document.getElementById("name");
let emailSpan = document.getElementById("email");
myForm.addEventListener("submit", e => {
e.preventDefault();
alert(`NAME: ${nameInput.value}, EMAİL : ${emailInput.value}`)
// select name , mail
nameSpan.innerText = nameInput.value;
emailSpan.innerText = emailInput.value;
// clear ınputs
nameInput.value = "";
emailInput.value = ""
})
showData();
function showData() {
nameInput.addEventListener("keyup", e => {
nameOutput.value = e.target.value;
})
emailInput.addEventListener("keyup", e => {
emailOutput.value = e.target.value;
})
}
<form id="myForm">
<input type="text" id="nameInput" placeholder="your name">
<input type="text" id="emailInput" placeholder="your email">
<button type="submit" id="getInputValue"> Get Input Value </button>
</form>
<div id="values" style="margin-top: 100px;">
<input type="text" placeholder="NAME" id="nameOutput">
<input type="text" placeholder="EMAİL" id="emailOutput">
</div>
<div>
<p>Your name : <span id="name"></span></p>
<p>Your email : <span id="email"></span></p>
</div>
All of my var statements uses identifiers:
var identifier = document.getElementById("somename");
So why am I getting a null error?
I ran this code in the Javascript runner and got the null error message. And in my browsers Firefox and Chrome I don't get any errors or warnings. When I run the code in the browser and click the button to activate the event handler, the form clears. It's not going to a server anyway. It's just practice. I'm taking a course in javascript and Dynamic HTML. If anybody care to look at my code and tell me what I'm doing wrong I'd appreciate it.
There's got to be something that I'm not getting right. Here is the script:
window.onload = function(){
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var loginName = document.getElementById("uname").value;
var myEmail = document.getElementById("email").value;
var pass1 = document.getElementById("password1").value;
var pass2 = document.getElementById("password2").value;
if(document.getElementById("uname").value == ""){
return false;
alert("Your user name can't be blank.");
};
if(pass1.value !== pass2.value){
get.documentElementById("signin").value.disabled = true;
return false;
alert("Please retype your password.");
}else if(pass1.value === pass2.value){
alert("Welcome!");
};
};
HTML
<body>
<form action = "" name = "form" method = "Post">
<label for="fname">First Name:</label><input type = "text" id = "fname"required></input>
<label for="lname">Last Name:</label><input type = "text" id = "lname" required></input>
<label for="uname">User Name:</label><input type = "text" id = "uname" required></input><br/>
<label for="password1">Password:</label><input type = "password" id = "password1"required ></input><br/>
<label for="password2">Verify Password:</label><input type = "password" id = "password2"required ></input><br/>
<label for="email">Email Address:</label><input type = "email" id = "email" required></input><br/>
<button type = "submit"id = "signin" onclick = "function()">Submit</button>
</form>
<script src="signUp.js"></script>
</body>
I cleaned up your code for you. There were several spots where you had errors (e.g., typing pass1.value instead of just pass1. This should work, but of course take time to study it to see what I changed and understand why. Here's a fiddle showing it working. Note that you should never expect this type of code to run in the "runners" that you've made reference to; the code here makes explicit reference to particular elements in the DOM, which the runners won't have. (Using a site like JSFiddle is better for this sort of thing, since you can put HTML into it as well).
var submitForm = function () {
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var loginName = document.getElementById("uname").value;
var myEmail = document.getElementById("email").value;
var pass1 = document.getElementById("password1").value;
var pass2 = document.getElementById("password2").value;
console.log(pass1, pass2);
if (document.getElementById("uname").value == "") {
alert("Your user name can't be blank.");
return false;
}
if (pass1 !== pass2) {
document.getElementById("signin").value.disabled = true;
alert("Please retype your password.");
return false;
} else if (pass1 === pass2) {
alert("Welcome!");
}
};
<body>
<form action="" name="form" method="POST">
<label for="fname">First Name:</label><input type ="text" id = "fname" required></input>
<label for="lname">Last Name:</label><input type = "text" id = "lname" required></input>
<label for="uname">User Name:</label><input type ="text" id ="uname" required></input><br/>
<label for="password1">Password:</label><input type="password" id="password1" required></input><br/>
<label for="password2">Verify Password:</label><input type="password" id="password2" required ></input><br/>
<label for="email">Email Address:</label><input type="email" id="email" required></input><br/>
<button type="submit" id="signin" onclick="submitForm()">Submit</button>
</form>
</body>
I have a registration page and I want to compare two passwords (input fields) to be equal before writing it to a websql database.
I cannot seem to get it to work.
Any ideas?
function addTodo() {
var todo = document.getElementById("todo");
var todo2 = document.getElementById("todo2");
if(todo != todo2) {
alert("Yours passwords do not match");
} else {
curatio.webdb.addTodo(todo.value);
todo.value = "";
alert("Your Registration was successfull");
setTimeout(function () {
window.location.href = "login.html";
}, 1000);
}
}
<div data-role="fieldcontain" >
<label for="todo">
Password
</label>
<input name="" id="todo" placeholder="" value="" type="password" required>
</div>
<div data-role="fieldcontain" >
<label for="todo2">
Retype your Password
</label>
<input name="" id="todo2" placeholder="" value="" type="password" required>
</div>
You're comparing the elements instead of their values.
var todo = document.getElementById("todo");
var todo2 = document.getElementById("todo2");
if(todo != todo2) { // Oops
todo and todo2 are 2 different <input> elements.
Try using .value:
if(todo.value !== todo2.value) {
You're comparing the actual elements, which will always be true (because they are both TextFields). Compair their values, like so:
var todo = document.getElementById("todo").value;
var todo2 = document.getElementById("todo2").value;
Either this or change
if(todo != todo2)
to
if(todo.value != todo2.value)
Another way is Object.is(password, confirm_password)
I am having difficulty validating a form in javascript. I'm currently checking just a text field and it doesn't work. My code is as followed:
index.html:
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>
Validation Form
</title>
<script type = "text/javascript" src ="vForm.js">
</script>
</head>
<body>
<form id = "myForm" action ="">
First name: <input type="text" name="fname"></br>
Last name: <input type="text" name="lname"></br>
Password: <input type="password" name="pass1"></br>
Re-enter password: <input type="password" name="pass2"></br>
Email: <input type="text" name="email"></br>
Phone: <input type="text" name="phone"></br>
Address: <input type="text" name="add"></br>
Date: <input type="date" name="date"></br>
Time: <input type="time" name="time"></br>
<input type="reset" name="reset">
<input type="submit" name="submit">
</form>
<script type = "text/javascript" src ="vFormRun.js">
</script>
</body>
</html>
vForm.js:
function validateForm()
{
var fname = document.getElementById("fname");
var lname = document.getElementById("lname");
var pass1 = document.getElementById("pass1");
var pass2 = document.getElementById("pass2");
var email = document.getElementById("email");
if(fname == "")
{
alert("Please enter first name")
return false;
}
else
{
return true;
}
}
vFormRun.js:
document.getElementById("myForm").onsubmit = validateForm;
You need to give .value to each of it. And also, give an id of the same name.
function validateForm()
{
var fname = document.getElementById("fname");
var lname = document.getElementById("lname");
var pass1 = document.getElementById("pass1");
var pass2 = document.getElementById("pass2");
var email = document.getElementById("email");
if(fname.value == "")
{
alert("Please enter first name")
return false;
}
else
{
return true;
}
}
document.getElementById("fname");
That will only work if you have an element with an ID of fname, which you do not.
You can set the ID attribute to an element like so:
<input type="text" name="fname" id="fname">
Alternatively, you can reference the form elements like this:
var fname = document.forms["myForm"]["fname"]
Then you want to get it's value property when comparing.
fname.value
The <br> tag is self closing, so it should be <br /> instead of </br>
Here is the solution...
function validateForm(form) {
var fname = form.fname,
lname = form.lname,
pass1 = form.pass1,
pass2 = form.pass2,
email = form.email;
if(fname && fname.value === "") {
alert("Please enter first name");
document.getElementById('result').innerHTML = 'Invalid';
return false;
}
document.getElementById('result').innerHTML = 'Passed';
return true;
}
<form id="myForm" action="" onsubmit="validateForm(this)">
First name: <input type="text" name="fname"><br/>
Last name: <input type="text" name="lname"><br/>
Password: <input type="password" name="pass1"><br/>
Re-enter password: <input type="password" name="pass2"><br/>
Email: <input type="text" name="email"><br/>
Phone: <input type="text" name="phone"><br/>
Address: <input type="text" name="add"><br/>
Date: <input type="date" name="date"><br/>
Time: <input type="time" name="time"><br/>
<input type="reset" name="reset">
<input type="submit" name="submit">
<p id="result">
</p>
</form>
There were a few issues here that I corrected.
I changed all of the var declarations to use one var declaration. This is a best practice.
In the if statement I added a check for the variable fname to make sure it exists and is not null (prevents a null reference error).
In the if statement you need to check the value attribute of the filed, not the field itself. In your old code if it is blank or not the field should be there and would have always returned true.
I changed the comparison to use === instead of ==. When using ==, if the value is "false" or 0 it will return true. See "Difference between == and === in JavaScript".
You were missing a semicolon at the end of the alert statement.
If the body of the if ends with a return then you do not need an else block. Cuts down the amount of code (downloads faster) and makes it easier to read.
Can anyone tell me whats wrong with this code, im validating a form making sure all the fields have text in them before anyone can submit. everything works until i put in the !='' var. I am sure the id's are correct
<script src="jquery.js" type="text/javascript" language="javascript"></script>
<script language="javascript">
$(document).ready(function() {
// declare the flags outside the other functions
var username_ready = false;
var email_ready = false;
function checkSubmitStatus() {
var emailvalue = $("#email").val();
var usernamevalue = $('#username').val();
var firstvalue = $('#first').val();
var lastvalue = $('#last').val();
var passwordvalue = $('#password').val();
if (username_ready && email_ready && emailvalue!='' && usernamevalue!='' && firstvalue!='' && lastvalue!='' && passwordvalue!=''){
$("#register").prop('disabled',false);
}
else {$("#register").prop('disabled',true);}
}
and here is my form code so you can see if thats the issue...
<p>First Name: <input id="first" type="text" name="name" maxlength="100"> </p>
<p>Last Name: <input id="last" type="text" name="name" maxlength="100"> </p>
<p> Email: <input type="text" name="email" id="email" maxlength="100" />
<span id="box" style="display:none"></span></p>
User Name : <input name="username" type="text" id="username" value="" maxlength="15" />
<span id="msgbox" style="display:none"></span>
<p> Password: <input id="password" type="password" name="password"> </p>
You spelt your variable name firstvalue incorrectly:
firstvale!=''
Edit
Move these 5 lines:
var emailvalue = $("#email").val();
var usernamevalue = $('#username').val();
var firstvalue = $('#first').val();
var lastvalue = $('#last').val();
var passwordvalue = $('#password').val();
From where they are to right under function checkSubmitStatus(){ and above your big if statement.
Where they are now, they are only assigned once, to the value of the form when the page first loads which I'm assuming at least one of them is empty.
You need to move those lines into your checkSubmitStatus() function so that they get updated whenever the function is called. The final result should look like:
var username_ready = false;
var email_ready = false;
function checkSubmitStatus() {
var emailvalue = $("#email").val();
var usernamevalue = $('#username').val();
var firstvalue = $('#first').val();
var lastvalue = $('#last').val();
var passwordvalue = $('#password').val();
if (username_ready && email_ready &&
emailvalue!='' && usernamevalue!='' &&
firstvalue!='' && lastvalue!='' && passwordvalue!=''){
$("#register").prop('disabled',false);
} else {
$("#register").prop('disabled',true);
}
}
Judging from your code, I get the feeling that it's copy-pasted together from different parts of your code. What might be happening is that emailvalue, usernamevalue etc are really out of scope at the time the checkSubmitStatus is called. I might also be wrong, but it's hard to tell more based on the provided code, since it seems to be alright.
You could do alert(emailvalue); before the if statement to see if you get undefined or some value. If it's undefined, you probably have a scope issue.
From the above code it also seems that you assign those variables values, before anything is really entered or the form is submitted.