Validation of a Simple Form - javascript

In process of learning JS. Trying to learn how to loop through an entire form, and have errors pointed out.
This is a hodgepodge that I cobbled together from various tutorials online.
Clearly it's not working.
What I am trying to do is to get the forms' entire collection of its elements, and loop through it, and anything that's blank, to have its error message printed somewhere on the same screen, be it above the form or underneath the textboxes itself.
This is what I have so far. Any help in getting this to work, or at least the concept of what I outlined? Simple and bite-size explanations if possible would be appreciated.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<form method="post" action="" id="myForm">
<div id="validation"></div>
<p><label>Name<br><input type="text" name="Name"></label></p>
<p><label>Email<br><input type="text" name="Email"></label></p>
<p><input type="submit" value="Submit"></p>
</form>
<script>
var formsCollection = document.forms[0];
for (var i = 0; i < formsCollection.elements.length; i++) {
if (formsCollection.elements.value.length == 0) {
form.elements.input.border = "1px solid red";
form.Name.style.backgroundColor = "#FFCCCC";
}
return true;
}
document.getElementById("myForm").onsubmit = function () {
return Validate(this);
};
</script>
</body>
</html>
EDIT
<script>
function Validate() {
var formsCollection = document.forms[0];
for (var i = 0; i < formsCollection.elements.length; i++) {
if (formsCollection.elements[i].value.length == 0) {
form.elements.input.border = "1px solid red";
form.Name.style.backgroundColor = "#FFCCCC";
}
return true;
}
document.getElementById("myForm").onsubmit = function () {
return Validate(this);
};
}
</script>

Full ans:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<form method="post" action="" id="myForm">
<div id="validation"></div>
<p><label>Name<br><input type="text" name="Name"></label></p>
<p><label>Email<br><input type="text" name="Email"></label></p>
<p><input type="submit" value="Submit"></p>
</form>
<script>
document.forms[0].onsubmit= function() {
var form = document.forms[0];
for (var i = 0; i < form.elements.length; i++) {
if (form.elements[i].value.length == 0) {
console.log(form.elements[i]);
form.elements[i].border = "1px solid red";
form.elements[i].style.backgroundColor = "#FFCCCC";
return false;
}
}
}
</script>
</body>
</html>
Several problems.
There seems to be no i in your for loop usage.
Try if (formsCollection.elements.value.length == 0) {
to if (formsCollection.elements[i].value.length == 0) {
Where is your Validate function?
Wrap var formsCollection ... END_OF_FOR_LOOP with function Validate(){ and }

Related

How to get the value of a checkbox using getelementbyID inside a form

I have a code which worked fine while I was testing it now I decided it to include it inside a form and it just does not want to work. If I remove the form tag it works and with the form tag it does not.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<script>
function action() {
var checkBox = document.getElementById("UPCheck");
if (checkBox.checked == true){
window.localStorage['username'] = document.getElementById('username').value;
window.localStorage['password'] = document.getElementById('password').value;
window.localStorage['unpwchecked'] = "yes";
alert("Saved!");
}
else
{
window.localStorage['username'] = "";
window.localStorage['password'] = "";
window.localStorage['unpwchecked'] = "";
}
}
function action2() {
document.getElementById('username').value = window.localStorage['username'];
document.getElementById('password').value = window.localStorage['password'];
}
</script>
</head>
<body>
<form>
<input type="text" id="username" name="username" value="">
<input type="text" id="password" name="password" value="">
Save username / password in cookies: <input type="checkbox" id="UPCheck" name="savelocalunpw">
<p><button onclick="action()" type="button">Save values!</button></p>
<p><button onclick="action2()" type="button">Load values!</button></p>
</form>
<script>
var alerted = localStorage.getItem('unpwchecked');
if (alerted == 'yes') {
document.getElementById('username').value = window.localStorage['username'];
document.getElementById('password').value = window.localStorage['password'];
document.getElementById("UPCheck").checked = true;
}
</script>
</body>
</html>
Remove the form tag and values are properly saved in localstorage.
The problem comes from the function name. If you rename
function action()
to
function action1()
and also modify
<button onclick="action1()" type="button">Save values!</button>
then your code will work.
I notices that without the form tag, the code works ok. If you add the form element, then you will get a console error, stating that action() is not a function. I'm just guessing that there is a conflict between the function name action() and the form attribute action
Try:
var isChecked = document.getElementById("UPCheck").checked;
Probably better practice to add an event handler for the buttons, that works with the form tags. Kind of interesting that it works with renaming the function.
JS
document.getElementById("save").addEventListener("click", function(){
var checkBox = document.getElementById("UPCheck");
if (checkBox.checked == true){
window.localStorage.username = document.getElementById('username').value;
window.localStorage.password = document.getElementById('password').value;
window.localStorage.unpwchecked = "yes";
alert("Saved!");
}
else
{
window.localStorage.username = "";
window.localStorage.password = "";
window.localStorage.unpwchecked = "";
}
});
document.getElementById("load").addEventListener("click", function(){
document.getElementById('username').value = window.localStorage.username;
document.getElementById('password').value = window.localStorage.password;
});
var alerted = localStorage.getItem('unpwchecked');
if (alerted == 'yes') {
document.getElementById('username').value = window.localStorage.username;
document.getElementById('password').value = window.localStorage.password;
document.getElementById("UPCheck").checked = true;
}
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<form>
<input type="text" id="username" name="username" value="">
<input type="text" id="password" name="password" value="">
Save username / password in cookies: <input type="checkbox" id="UPCheck" name="savelocalunpw">
<p><button id = "save" type="button">Save values!</button></p>
<p><button id = "load" type="button">Load values!</button></p>
</form>
</body>
</html>
You can use "dot" notation for localStorage.

Even after validation failed the new page is redirected

I am implementing a simple code just to figure out why validation is not working in my browser.
But validation is not working. Idk y.
It is just redirecting to next page
newjsp.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script>
function validation()
{
var a=document.form1.txt1.value;
if(a=="")
{
alert("Hey");
return false;
}
return true;
}
</script>
</head>
<body>
<form id="form1" onsubmit="return validation(this)" action="newjsp1.jsp">
<input type="text" id="txt1">
<input type="submit" id="sub">
</form>
</body>
Use opposite logic - something must be OK, then turn TRUE, in all other cases, return FALSE.
function validation()
{
var a = document.getElementById('txt1').value;
if (typeof a != "undefined" && a != "")
{
// `a` is in very good condition :)
return true;
}
alert('hey');
return false;
}
I think, your document.form1.txt1.value is not filled correctly, so your value a is probably undefined and not "", so it will return TRUE.
Try to debug with console.log(a);
And finally, use var a = document.getElementById('txt1').value;, just in case :)
instead of form id use name
<script>
function validation()
{
var a=document.form1.txt1.value;
console.log(a);
if(a=='')
{
alert("Hey");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="form1" onsubmit="return validation(this)" action="newjsp1.jsp">
<input type="text" id="txt1">
<input type="submit" id="sub">
</form>
</body>
Update
Do not use this as a function parameter. this is a keyword. Use any other variable. Something like this
function validation(form) {
var a=form.txt1.value;
if(a==="") {
window.alert("Hey");
return false;
}
return true;
}
When the form is like this
<form name="form1" onsubmit="return validation(this)" action="newjsp1.jsp">
....
</form>
Try document.forms.form1.txt1.value;
function validation(){
var a=document.forms.form1.txt1.value;
if(a==""){
alert("Hey");
return false;
}
return true;
}
Check the demo http://jsbin.com/vuxoha/1/edit

piece of html+javascript that finds if number from an input is prime then displays the result

School project. I must design a page that contains an input box, a button that sends the entered number to the function, and a paragraph that displays the result. Here's my progress as of now, problem is it just says "false" everytime. Sorry for the triviality of the question, i'm a total newb with web coding.
<!DOCTYPE html>
<html>
<head>
<script>
function isPrime($n)
{
$i=2;
if ($n==2){
return true;
}
$sqrtN = sqrt($n);
while ($i<= $sqrtN){
if ($n % $i ==0){
return false;
}
$i++;
}
return true;
}
</script>
</head>
<body>
Value: <input type="number" id="n"><br>
<input type="submit" value="Send" onclick="isPrime(n)">
</form>
<p id="derp">sdvfsdg</p>
<script>
document.getElementById("derp").innerHTML = isPrime(n);
</script>
</body>
</html>
Basically you are setting the content of the derp once and for all before pressing the button
function isPrime($n)
{
$i=2;
if ($n==2){
document.getElementById("derp").innerHTML = "True";
}
$sqrtN = sqrt($n);
while ($i<= $sqrtN){
if ($n % $i ==0){
document.getElementById("derp").innerHTML = "False";
}
$i++;
}
document.getElementById("derp").innerHTML = "True";
}
And not sure you really need the $ everywhere - that's a PHP thing
You had not used input field value at all, that was your mistake
Value:
<input type="number" id="n">
<br>
<input type="submit" value="Sebd" onclick="x()">
</form>
<p id="derp">sdvfsdg</p>
<div id="try">jdfs</div>
<script>
function x() {
document.getElementById('derp').innerHTML = isPrime(Number(document.getElementById('n').value));
}
function isPrime(n) {
i = 2;
if (n == 2) {
return true;
}
sqrtN = Math.sqrt(n);
document.getElementById('try').innerHTML = n;
while (i <= sqrtN) {
document.getElementById('try').innerHTML = 'try';
if (n % i == 0) {
return false;
}
i++;
}
return true;
}
</script>
Here's the code that'll work for your case... You should execute the code on click AFTER entering the value
<!DOCTYPE html>
<html>
<head>
<script>
</script>
</head>
<body>
Value: <input type="number" id="n"><br>
<input type="submit" value="Send" onclick="checkPrime()"> <!--use function on click-->
</form>
<p id="derp">sdvfsdg</p>
<script>
function isPrime(num)
{
var isPrime = true; //initially set to true
for(var i=2; i<num; i++){
if(num%i == 0){ //if the num gets divide by any other number except itself
isPrime = false;
}
}
return isPrime;
}
function checkPrime(){ //function that gets called on send button click
var number = document.getElementById("n").value; //get the value of input
number = parseInt(number); //since it's a string,convert it into number
document.getElementById("derp").innerHTML = isPrime(number); //check if prime and display result
}
</script>
</body>
</html>

Having trouble making hidden/visible error message

I am making a contact form, which includes name, email and a message which can then be submitted. If any of the three fields are null an error message is shown which I have working. The word "error" appears in all three field boxes. My issue is that I am trying to add a single error message which will be hidden and only appear if an error is made, this will say "Please fill in all fields before submitting"
I am new to ColdFusion and mixing HTML with JavaScript. So I was wondering if anyone could please give me some tips as to what I have done wrong. I have tried to manipulate it many ways and tried adding a div for this message in my CSS. But to no avail, the message always shows up. It doesn't stay hidden when needed.
I would really appreciate any information or help anyone could give, I am so confused and have searched the whole web looking for this info.
Here is my code:
var requiredFields = ["name", "email", "message"];
function checkContactForm() {
var myForm = document.forms[0];
for (i in requiredFields) {
fieldName = requiredFields[i];
if (!myForm[fieldName].value || myForm[fieldName].value == "Error") {
myForm[fieldName].style.color = "#f66";
myForm[fieldName].value = "Error";
var emptyFields = true;
}
}
if (!emptyFields) {
myForm.submit();
} else {
if (document.getElementById("name == null || email == null || message == null")
document.getElementById("errormessage").style.visibility = "visible";
} else {
document.getElementById("errormessage").style.visibility = "hidden";
}
}
function resetField(myField) {
if (myField.value == "Error") {
myField.style.color = "#000";
myField.value = "";
}
}
function resetForm(myForm) {
var myForm = document.forms[0];
for (i in requiredFields) {
fieldName = requiredFields[i];
myForm[fieldName].style.color = "#000";
}
}
and here is the CSS for my error message:
#errormessage {
font-style: italic;
text-indent: 10px;
border: dotted;
border-width: 1px;
}
There is a much easier way to do form validation with ColdFusion. If you use <cfform> and <cfinput> tags then a lot of JavaScript is written for you. All you have to do is something like this:
<cfform action="whereever">
<cfinput type="text" name="fred" required="yes" message="fred is required">
<input type="submit">
</cfform>
It's not as fancy as what you are attempting, but it's simple and it's effective.
Please go through the below code and see what you have done wrong.
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body onload="checkContactForm();">
<style type="text/css">
#errormessage {
font-style: italic;
text-indent: 10px;
border: dotted;
border-width: 1px;
}
</style>
<script type="text/javascript">
var requiredFields = ["name", "email", "message"];
function checkContactForm() {
var myForm = document.forms[0];
for (i in requiredFields) {
fieldName = requiredFields[i];
if (!myForm[fieldName].value || myForm[fieldName].value == "Error") {
myForm[fieldName].style.color = "#f66";
myForm[fieldName].value = "Error";
var emptyFields = true;
}
}
if (!emptyFields) {
myForm.submit();
}
else
{
if (emptyFields) {
document.getElementById("errormessage").innerHTML = "Validation Error";
document.getElementById("errormessage").style.visibility = "visible";
}
else
{
document.getElementById("errormessage").style.visibility = "hidden";
}
}
}
function resetField(myField) {
if (myField.value == "Error") {
myField.style.color = "#000";
myField.value = "";
}
}
function resetForm(myForm) {
var myForm = document.forms[0];
for (i in requiredFields) {
fieldName = requiredFields[i];
myForm[fieldName].style.color = "#000";
}
}
</script>
<div id="errormessage"></div>
<form action="STO1.html" method="POST" name="myForm">
<input type="text" name="name" id="name"/>
<input type="text" name="email" id="email"/>
<input type="text" name="message" id="message"/>
<input type="submit"/>
</form>
</body>
</html>

Cant remove childnode without making childNode (message) not showing at all

I've have tried alot of different ways with removing the child and nothing has worked so faar, well it has to some degree, either i have no messages or i keep getting message that just add to the span without deleting the other
Tried reading up on how to remove the child, and have tried every different ways i've found to remove it, my code might be wrong on creating the child and append it etc. since it's the first time i use this way. Been trying with a while loop to remove, and the one that is already outcommented in the code, and with firstChild. and with different names instead of msg.
My code looks like this in my script:
function validateName(input, id)
{
var res = true;
var msg = document.getElementById(id);
var error = document.createElement("span");
var errorMsg = "";
if (input == "" || input < 2) {
res = false;
// removeChildren(msg);
errorMsg = document.createTextNode("Input is to short!");
error.appendChild(errorMsg);
id.appendChild(error);
}
if (input >= 2 && input.match(/\d/)) {
res = false;
// removeChildren(msg);
errorMsg = document.createTextNode("Name contains a number!");
error.appendChild(errorMsg);
id.appendChild(error);
}
if (input >= 2 && !input.match(/\d/)) {
res = true;
// removeChildren(msg);
}
return res;
}
My small test page:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="Validator.js"></script>
<script>
function v1(e,id) {
if(validateName(document.form1.namefield.value, id) == false) {
document.getElementById("be").src="NotOkSmall.jpg";
}
if(validateName(document.form1.namefield.value) == true) {
document.getElementById("be").src="OkSmall.jpg";
}
}
</script>
</head>
<body>
<h1>Validation testing, HO!</h1>
<form name="form1" action="submit">
<div id="div1">
<input type="text" name ="namefield" id="f1" onkeydown="v1(be, div1)" >
<image id="be" src="NotOkSmall.jpg" alt="OkSmall.jpg" />
</div>
<input type="button" value="GO" onClick="v1(be)">
</form>
</body>
</html>
If anyone have any ideas to make it work I for one, would be a very happy guy :), as i have said before i am not even sure the creation of child is the correct way in this case. but as it works when i have removed removeChildren, it does write the correct messages, just dont delete any of them. So something must work..
Thanks.
You had some errors in your code like id.appendChild(error); where you had to use msg.appendChild(error);. Anyway I don't see a need to append/remove child nodes in this case. Just use hidden error placeholder and show it when you want to display an error message.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSP Page</title>
<script src="Validator.js"></script>
<script>
function v1(imgId) {
var img = document.getElementById(imgId),
val = document.form1.namefield.value;
img.src = img.alt = validateName(val)
? "OkSmall.jpg"
: "NotOkSmall.jpg";
}
</script>
</head>
<body>
<h1>Validation testing, HO!</h1>
<form name="form1" action="submit">
<div id="div1">
<input type="text" name ="namefield" id="f1" onkeyup="v1('be');" >
<image id="be" src="NotOkSmall.jpg" alt="NotOkSmall.jpg" />
<span id="error-message" class="invis"></span>
</div>
<input type="button" value="GO" onClick="v1('be');">
</form>
</body>
</html>​​​​​​​​​
CSS:
​.invis {
display: none;
}​
JavaScript:
function validateName(input) {
var res = true,
errorMsg,
errorContainer = document.getElementById('error-message');
if(input.length < 2) {
res = false;
errorMsg = "Input is to short!";
}
if(input.length >= 2 && /\d/.test(input)) {
res = false;
errorMsg = "Name contains a number!";
}
if(res) {
errorContainer.style.display = 'none';
} else {
errorContainer.innerHTML = errorMsg;
errorContainer.style.display = 'inline';
}
return res;
}​
DEMO

Categories

Resources