Form Validation with Array and User Input - javascript

I have set up a user input box to enter a number (1 through 3) to show that many FAQS on my site. I also would like to use a form validation to inform the user that they have left the input box empty. The array prints just fine with the user input, but the form validation does not throw an alert when the input box is left empty.
Here is the HTML:
<div id="block3"><br/><br/>
<a name="FAQs"><img id="img2" src="pic2.JPG" alt="Computer" />
<h2>FAQs</h2></a>
<p id="p01">
Enter a number (up to 3):
<input type="text" id="FAQS_list" placeholder="Enter Number Here" />, and
<button value="Click" onclick="listFAQS()" onSubmit="return validateForm()">Click</button> to see that many Frequently Asked Questions.<br/><br/><br/></p>
<p id="FAQS"></p>
<script src="expExternal.js" type="text/javascript"></script>
and here is the Javascript
function listFAQS() {var arrayFAQ = ["FAQ1", "FAQ2", "FAQ3"];
var n = document.getElementById('FAQS_list').value;
var x = 0;
var text = "";
while (x < n) {
text += arrayFAQ[x] + "<br>";
x++;}
document.getElementById('FAQS').innerHTML = text;
}
// Form Validation
function validateForm() {
var y = document.getElementById("FAQS_list").value;
if (y == "") {
alert("Please enter a number.");
return false;
}
}
Any help would be greatly appreciated!

First, you have to control size of your arrayFAQ before or in while loop statment, otherwise your list contain additional n-3 number of undefined.
while ( n <= arrayFAQ.length && x < n ) {
text += arrayFAQ[x] + "<br>";
x++;
}
If you want add new elements to the array arrayFAQ and display them all,
add one if block after
var n = document.getElementById('FAQS_list').value;
like this
if (isNaN(n)) {
arrayFAQ.push(n);
n = arrayFAQ.length;
}

You need to use the form tag and onsubmit event handler.
Modify the type of the button to submit.
Please see the code below for reference:
function listFAQS() {
var arrayFAQ = ["FAQ1", "FAQ2", "FAQ3"];
var n = document.getElementById('FAQS_list').value;
var x = 0;
var text = "";
while (x < n) {
text += arrayFAQ[x] + "<br>";
x++;
}
document.getElementById('FAQS').innerHTML = text;
}
// Form Validation
function validateForm() {
var y = document.getElementById("FAQS_list").value;
if (y == "") {
alert("Please enter a number.");
return false;
}
}
<form onsubmit="return validateForm()" action="/" method="post">
<a name="FAQs">
<img id="img2" src="pic2.JPG" alt="Computer" />
<h2>FAQs</h2>
</a>
<p id="p01">
Enter a number (up to 3):
<input type="text" id="FAQS_list" placeholder="Enter Number Here" />, and
<button type="submit" value="Click" onclick="listFAQS()">Click</button> to see that many Frequently Asked Questions.<br /><br /><br />
</p>
<p id="FAQS"></p>
</form>

Related

Submit button clearing out form, and not displaying anything

I'm trying to create a fun little registration sheet to practice my validation. When I hit the submit button I have two issues. The first issue is my form keeps clearing every input field the moment I hit submit. I tried to use have my onclick = return false but this did nothing. The next issue I'm having is when I hit submit nothing happens at all. I'm not sure where I have messed up but if someone could point it out to me.
<!-- create a function to validate and pass information along -->
function Validation() {
<!-- declare variables -->
var ifErrors = false;
<!-- create the array to display error messages when cycled through -->
var ErrorMessage = new Array();
var myUserName = document.getElementById("txtUsername").value;
var myPassword = document.getElementById("txtPassword").value;
var myFirstName = document.getElementById("txtFirstName").value;
var myLastName = document.getElementById("txtLastName").value;
var myDateOfBirth = document.getElementById("txtDateOfBirth").value;
var myEmail = document.getElementById("txtEmail").value;
var myPhoneNumber = document.getElementById("txtPhoneNumber").value;
var LettersOnly = /^[a-z]+$/;
var DateOfBirthValidate = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
var Dates = new Date();
var DateSupplied = document.getElementById("txtDateOfBirth").value;
var PhoneNumberValidate = /^\([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
<!-- Begin validation -->
//validate for username being blank
if (myUserName = "")
{
ifErrors = true;
ErrorMessage.push('Username is required');
}
//validate for username not being 8 or more characters
if(myUserName.length < 8)
{
ifErrors = true;
ErrorMessage.push('Username must be 8 or more characters');
}
//validate for password being blank
if (myPassword == "")
{
ifErrors = true;
ErrorMessage.push('Password is required');
}
//validate for password not being 8 or more characters
if (myPassword.length < 8)
{
ifErrors = true;
ErrorMessage.push('Password must be 8 or more characters');
}
//validate for first name being blank
if (myFirstName == "")
{
ifErrors = true;
ErrorMessage.push('First name can not be blank');
}
//validate for last name being blank
if (myLastName == "")
{
ifErrors = true;
ErrorMessage.push('Last name can not be blank');
}
//validate for date of birth being blank
if (myDateOfBirth == "")
{
ifErrors = true;
ErrorMessage.push('Last name can not be blank');
}
//validate for date of birth not being formatted like (MM/DD/YYYY)
if (document.getElementById("txtDateOfBirth").value.length > 1)
{
if (! (txtDateOfBirth,valueOf().match(DateOfBirthValidate)));
{
ifErrors = true;
ErrorMessage.push('not a valid date of birth');
}
}
//create a variable to hold date, and see if it's greater than the current date
DateSupplied = new Date(DateSupplied);
if (DateSupplied > Dates)
{
ifErrors = true;
ErrorMessage.push('Date supplied can not be greater than the current date');
}
//va;idate for phone number
if (document.getElementById("txtPhoneNumber").value.length > 1)
{
if (! (txtPhoneNumber.valueOf().match(PhoneNumberValidate)))
{
ifErrors = true;
ErrorMessage.push('Phone number is not valid');
}
}
//successful validation
if (ifErrors == false)
{
ifErrors = true;
alert('Your registration has been processed');
//document.getElementById("RegisterForm").reset();
}
//Display list of messages in list
var DisplayMessage = "";
ErrorMessage.forEach(function (message)
{
DisplayMessage += "<li>" + message + "</li>";
}
);
document.getElementById("Errors").innerHTML = DisplayMessage;
}
<body>
<h3>Registration</h3>
<div>
<ul id="Errors"> </ul>
</div>
<br/>
<form ="RegisterForm">
<label id="lblUsername">Username:</label>
<input type="text" id="txtUsername" />
<br/>
<label id="lblPassword">Password:</label>
<input type="password" id="txtPassword" />
<br/>
<label id="lblFirstName">First Name:</label>
<input type="text" id="txtFirstName" />
<br/>
<label id="lblLastName">Last Name:</label>
<input type="text" id="txtLastName" />
<br/>
<label id="lblDateOfBirth">Date of Birth:</label>
<input type="text" id="txtDateOfBirth" />
<br/>
<label id="lblEmail">Email:</label>
<input type="text" id="txtEmail" />
<br/>
<label id="lblPhoneNumber">Email:</label>
<input type="text" id="txtPhoneNumber" />
<br/>
<input type="submit" value="Submit" onclick="Validation(); return false;" />
<input type="reset" value="reset Form" />
</form>
</body>
return false; does not stop the form from being submitted.
In order to achieve this behavior, you have to call .preventDefault() on the click event of the <input>, or on the submit event of the <form>. Example:
<form>
<input type="submit" onclick="someFn(event)">
</form>
<script>
function someFn(e) {
e.preventDefault();
console.log('form not submitted...');
}
</script>
To prevent all submit events in one go (regardless of which form element initiated it) you can call .preventDefault() on the form's onsubmit handler parameter (which is the submit event):
<form onsubmit="someFn(event)">
<input type="submit">
<button>Submit</button>
</form>
<script>
function someFn(e) {
e.preventDefault();
console.log('form not submitted...');
}
</script>
As a side-note, the submit input does not clear out your form. It sends it.
Because you haven't specified an action attribute on your <form> element, the submission is sent to the current URL.
Which, in practice, reloads the page.
Which, in practice renders a brand new instance of the form, obviously empty.
This is also the reason why "nothing happens at all". The default browser behavior when submitting a form is to actually load the <form>'s action URL (whether it's explicitly specified or not). You're navigating to that URL, along with the form's values. Which means you're not allowing the browser to finish running the code in Validation();. To wait around and see the results of Validation function, you have to prevent the default form submission behavior.
Docs:
<form>: MDN, HTML (Living Standard)
<input type="submit">: MDN, HTML (Living Standard)
Event.preventDefault(): MDN, DOM (Living Standard)

showing the length of a input

How do I enable input2 if enable 1 has input within it (basically re-enabling it), I'm still a beginner and have no idea to do this.
<form id="form1">
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2" disabled="disabled">
<script language="javascript">
function valid() {
var firstTag = document.getElementById("text1").length;
var min = 1;
if (firstTag > min)
//if the text entered is longer than 1 alert to screen
{
//enable the text2 tag
}
}
//once input from text1 is entered launch this function
</script>
</form>
if i understand your question correctly, you want to enable the second input as long as the first input have value in it?
then use dom to change the disabled state of that input
if(firstTag > min)
//if the text entered is longer than 1 alert to screen
{
//enable the text2 tag
document.getElementById("text2").disabled = false;
}
Please try this code :
var text1 = document.getElementById("text1");
text1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("text2").disabled = false;
} else {
document.getElementById("text2").disabled = true;
}
}
<input type="text" id="text1">
<input type="text" id="text2" disabled="disabled">
I think you should use .value to get the value. And, then test its .length. That is firstTag should be:
var firstTag = document.getElementById("text1").value.length;
And, the complete function should be:
function valid() {
var min = 1;
var firstTag = document.getElementById("text1");
var secondTag = document.getElementById("text2");
if (firstTag.length > min) {
secondTag.disabled = false
} else {
secondTag.disabled = true
}
}
Let me know if that works.
You can use the .disabled property of the second element. It is a boolean property (true/false).
Also note that you need to use .value to retrieve the text of an input element.
Demo:
function valid() {
var text = document.getElementById("text1").value;
var minLength = 1;
document.getElementById("text2").disabled = text.length < minLength;
}
valid(); // run it at least once on start
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2">
I would just change #Korat code event to keyup like this:
<div>
<input type="text" id="in1" onkeyup="enablesecond()";/>
<input type="text" id="in2" disabled="true"/>
</div>
<script>
var text1 = document.getElementById("in1");
text1.onkeyup = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("in2").disabled = false;
} else {
document.getElementById("in2").disabled = true;
}
}
</script>
I tried to create my own so that I could automate this for more than just two inputs although the output is always set to null, is it that I cannot give text2's id from text1?
<div id="content">
<form id="form1">
<input type="text" id="text1" onkeyup="valid(this.id,text2)">
<input type="text" id="text2" disabled="disabled">
<script language ="javascript">
function valid(firstID,secondID){
var firstTag = document.getElementById(firstID).value.length;
var min = 0;
if(firstTag > min)
//if the text entered is longer than 1 alert to screen
{
document.getElementById(secondID).disabled = false;
}
if(firstTag == 0){
document.getElementById(secondID).disabled = true;
}
}
//once input from text1 is entered launch this function
</script>
</form>
First, you have to correct your code "document.getElementById("text1").length" to "document.getElementById("text1").value.length".
Second, there are two ways you can remove disabled property.
1) Jquery - $('#text2').prop('disabled', false);
2) Javascript - document.getElementById("text2").disabled = false;
Below is the example using javascript,
function valid() {
var firstTag = document.getElementById("text1").value.length;
var min = 1;
if (firstTag > min) {
document.getElementById("text2").disabled = false;
}
else
{
document.getElementById("text2").disabled = true;
}
}
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2" disabled="disabled">
If I understand you correctly, what you are asking is how to remove the disabled attribute (enable) from the second input when more than 1 character has been entered into the first input field.
You can to use the oninput event. This will call your function every time a new character is added to the first input field. Then you just need to set the second input field's disabled attribute to false.
Here is a working example.
Run this example at Repl.it
<!DOCTYPE html>
<html>
<body>
<!-- Call enableInput2 on input event -->
<input id="input1" oninput="enableInput2()">
<input id="input2" disabled>
<script>
function enableInput2() {
// get the text from the input1 field
var input1 = document.getElementById("input1").value;
if (input1.length > 1) {
// enable input2 by setting disabled attribute to 'false'
document.getElementById("input2").disabled = false;
} else {
// disable input2 once there is 1 or less characters in input1
document.getElementById("input2").disabled = true;
}
}
</script>
</body>
</html>
NOTE: It is better practice to use addEventListener instead of putting event handlers (e.g. onclick, oninput, etc.) directly into HTML.

How to prevent a form submit if some of the input areas are not filled

as the title says i need help with this part of the code
function myFunction() {
var x,t,y,z,u;
i need to use this part to check if everything is filled, and if it isnt the form must not be submitted
document.getElementById("gumb").onclick=function(event){
var slanje_forme=true;
if (slanje_forme!=true)event.preventDefault();
}
x = document.getElementById("NazivProizvoda").value;
t = document.getElementById("sifra").value;
y = document.getElementById("kategorija").value;
z = document.getElementById("opisProizvoda").value;
u = document.getElementById("cijena").value;
if (isNaN(x) || x.length < 5 || x.length > 30) {
document.getElementById("demo").innerHTML = "Naziv mora imati 5 do 30znakova!";
NazivProizvoda.style.border="1px red";
}
else if(isNaN(t) || t.length != 10)
{ document.getElementById("demo1").innerHTML = "Sifra mora imati 10 znakova";
sifra.style.border="1px red";
}
else if(isNaN(z) || z.length < 10 || z.length > 100)
{document.getElementById("demo2").innerHTML = "Opis mora biti izmedu 10 i 100 znakova!";
opisProizvoda.style.border="1px red";
}
else if(isNaN(u))
{ document.getElementById("demo3").innerHTML = "Cijena mora biti napisana";
cijena.style.border="1px red";
}
<!--if else(isNaN(y) || t.length != 10)-->
<!--{}-->
else {
text = "Input OK";
}
document.getElementById("demo4").innerHTML = text;
}
my problem is that i dont know how to wrap all of the if statements within the
preventDefault() or
return false,
do i need to write it like this
else if(isNaN(u))
{ document.getElementById("demo3").innerHTML ="Cijena mora biti napisana";
cijena.style.border="1px red";
}
HTML
Wrap your form controls in a <form> tag.
Add required attribute to each form control that needs the user to complete.
See Demo 1
JavaScript
Programatically this can be done with setAttribute(). In Demo 2, we are using the HTMLFormControlsCollection API to reference all <form> tags and their form controls. Although some form controls do not need the required attribute, it is harmless yet it is messy markup. removeAttribute() method can be used to clean them up or a more precise method could be used like querySelectorAll() in Demo 3.
See Demo 2 and Demo 3
Testing
Click the Submit button with and then without text in <input> text tag. In each demo the <form> tag is setup to send to a live test server. Upon a successful submission of data the test server will send a response. If an <input> tag is empty, the submit event is cancelled and a tooltip will remind the user to enter data in the applicable form control.
Demo 1
<form id='F' action="https://httpbin.org/post" method="post">
<label>Name: </label>
<input id="F0" name='F0' required placeholder="First" >
<input id="F1" name='F1' required placeholder="Last">
<input type="submit">
</form>
Demo 2
const F = document.forms.F;
const fx = F.elements;
for (let f = 0; f < fx.length; f++) {
fx[f].setAttribute("required", true);
}
<form id='F' action="https://httpbin.org/post" method="post">
<label>Name: </label>
<input id="F0" name='F0' placeholder="First">
<input id="F1" name='F1' placeholder="Last">
<input type="submit">
</form>
Demo 3
var inputs = document.querySelectorAll('input[type=text]');
inputs.forEach(function(fc, idx, inputs) {
fc.setAttribute("required", true);
});
<form id='F' action="https://httpbin.org/post" method="post">
<label>Name: </label>
<input id="F0" name='F0' type="text" placeholder="First">
<input id="F1" name='F1' type="text" placeholder="Last">
<input type="submit">
</form>

See length of value in text box

I want to be able to type a word into the text box and then click a button underneath which will issue an alert if the number of letters is below 5.
Type in words to see how long they are: <input type="text" id="txtBox" name="txtBox" value="banter"/>
<button onclick="myFunction()">Try It</button>
<script type="text/javascript">
function myFunction() {
var x = document.getElementById['txtBox'];
if (x.length < 5) {
alert('please enter at least 5 characters');
return false;
}
}
</script>
Here x is an element not a value
So change the x.length to x.value.length
Type in words to see how long they are: <input type="text" id="txtBox" name="txtBox" value="banter"/>
<button onclick="myFunction()">Try It</button>
<script type="text/javascript">
function myFunction() {
var x = document.getElementById('txtBox');
if (x.value.length < 5) {
console.log(x.length);
alert('please enter at least 5 characters');
}
}
</script>
Make your var x = document.getElementById['txtBox']; to var x = document.getElementById('txtbox');
Two things: functions are called with (), not [], and you need to check the length of the element's value rather that of the element itself.
function myFunction() {
var element = document.getElementById('txtBox');
if (x.value.length < 5) {
alert('please enter at least 5 characters');
return false;
}
}
Please, make the following change in your code and it will work:
var x = document.getElementById('txtBox').value;

Checking if integer JavaScript forms

I have begun learning javascript and I cannot get the security code part of my form (and I have yet to fix the other things such as card number) to bring up an alert if they have not entered 3 integers, I can get it to alert if the person doesnt enter 3 ints/strings/symbols etc... but > or < 3. However I cannot get it to alert the user if the things they pass are not integers. Thank you!.
edit: so the issue im trying to solve is how to run my is_int function on the theForm.cvs.value im sorry if im unclear its all a bit messy.
<script type="text/JavaScript">
function is_int(value){
if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
return true;
} else {
return false;
}
};
function verification(theForm) {
content = "";
var cardLen = (theForm.cardLength.value).length;
var securitycode = new is_int(theForm.cvs.value);
if (cardLen !== 16) {
content += "Please make sure you've entered 16 digits.";
}
if ((theForm.userName.value).length === 0) {
content += "Please make sure you've entered the correct name.";
}
if ((theForm.month.value) < 1 || theForm.month.value > 12 || theForm.month.value === "" || theForm.month.value === "MM") {
content += "Please make sure the you've entered the correct month.";
}
if ((theForm.year.value) < 2016 || ((theForm.year.value) === "" )) {
content += "Please make sure you've entered the correct expiry year.";
}
if ( !securitycode || ( (theForm.cvs.value).length !== 3) ) {
content += "Please make sure you've entered the correct security code.";
}
if (!content == "") {
alert (content); return false;
}
};
</script>
</head>
<body>
<br>
<br>
<br>
<center><h1>Checkout:</h1></center>
<div style="position:absolute; left:600px; top:200px;">
<form name="myForm" class="theForm" onSubmit="return verification(this)" >
Card Number: Expiration:
<br>
<input type="text" name="cardLength"> <input type="text" name="month" style="width:30px" value="MM"> - <input type="text" name="year" style="width:30px" value="YY">
<br>
Name: Security Code:
<br>
<input type="text" name="userName"> <input type="text" name="cvs" style="width:30px">
<br>
<br>
<input type="submit" value="Submit">
</form>
</div>
You don't want to create a new is_int. New creates an instance of an object and calls its constructor, but you just need to get a return value from a function.
if ( !is_int(theForm.cvs.value) || theForm.cvs.value.length !== 3 ) {
content += "Please make sure you've entered the correct security code.";
}

Categories