Javascript Setting Cookie to Remember form Submission - javascript

I've managed to create a form and set a cookie to remember that the user has submitted the form, but the code looks very complicated. Is there not a simpler way to do this? What can I remove? I am NOT SAVING any input data. I just need to ensure that a user fills out the form and is then redirected to the index page. Then when they try to open the page again, they don't have to fill out the form.
<html>
<head>
<title>Document Title</title>
<script type="text/javascript">
cookie_name="landasp"
expdays=365
function set_cookie(name, value, expires, path, domain, secure){
if (!expires){expires = new Date()}
document.cookie = name + "=" + escape(value) +
((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
((path == null) ? "" : "; path=" + path) +
((domain == null) ? "" : "; domain=" + domain) +
((secure == null) ? "" : "; secure");
}
function get_cookie(name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg){
return get_cookie_val(j);
}
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function get_cookie_val(offset){
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
function saving_cookie(){
var expdate = new Date ();
expdate.setTime (expdate.getTime() + (expdays*24*60*60*1000));
Data="cooked"
set_cookie(cookie_name,Data,expdate)
}
function get_cookie_data(){
inf=get_cookie(cookie_name)
if(!inf){
document.getElementById("display1").style.display="block"
}
else{
document.getElementById("display2").style.display="block"
}
}
</script>
</head>
<body onload="get_cookie_data()">
<div id="display1" style="display:none">
<div class="register">
<form action="index.html" onsubmit="saving_cookie()">
<div>Name<br>
<input name="name" type="text" id="name" class="inputf">
<br>Tel<br>
<input name="tel" type="text" id="tel" class="inputf">
<br><br>
<input type="submit" name="Submit" value="Submit" class="button1">
</div>
</form>
</div>
<div id="display2" style="display:none">
<div class="register">
<p><strong>REGISTERED</strong></p>
</div>
</div>
</body>
</html>

Yes, the cookie scripts are normally that big. You can externalise them in a jsfile
However if you do not need the cookie on the server, we nowadays use sessionStorage or localStorage
Also reversing the test
NOTE this script completely replaces yours
const cookie_name = "landasp";
window.addEventListener("load", function() {
const inf = localStorage.getItem(cookie_name);
if (inf) {
document.getElementById("display2").style.display = "block"
setTimeout(function() {location.replace("index.html"},2000)
} else {
document.getElementById("display1").style.display = "block"
}
document.getElementById("regForm").addEventListener("submit", function() {
localStorage.setItem(cookie_name, "done");
})
})
adding an ID to the form and removing inline event handlers
<div id="display1" style="display:none">
<div class="register">
<form action="index.html" id="regForm">
<div>Name<br>
<input name="name" type="text" id="name" class="inputf">
<br>Tel<br>
<input name="tel" type="text" id="tel" class="inputf">
<br><br>
<input type="submit" name="Submit" value="Submit" class="button1">
</div>
</form>
</div>
<div id="display2" style="display:none">
<div class="register">
<p><strong>REGISTERED</strong></p>
</div>
</div>
</div>

Related

Regular Expression always false

So I am writing some javascript to check if a user inputs a gmail address.
At the moment I have the code thats below, but no matter what I do it is giving me false. even when the input has #gmail.com...I feel that the mistake is how I am grabbing the user input in a variable and then testing it with test().
Javascript:
<script>
function validationCheck() {
var email = document.getElementById("inputEmail");
var gmailPatt = /#gmail.com/i;
var emailMatch = gmailPatt.test(email);
if (emailMatch == false || emailMatch == true) {
document.getElementById("emailError").innerHTML =
"<p>" + emailMatch + "</p>";
} else {
}
}
</script>
html
<form>
<div class="form-group row">
<div>
<label for="inputEmail" class="col-sm-1">Email:</label>
<input
type="text"
class="form-control col-sm-1"
id="inputEmail"
placeholder="username#gmail.com"
/>
<p id="emailError"></p>
</div>
</div>
<button type="button" onclick="validationCheck()">Check</button>
</form>
You need to check the value of the input, var emailMatch = gmailPatt.test(email.value);
function validationCheck() {
var email = document.getElementById("inputEmail");
var gmailPatt = /#gmail.com/i;
var emailMatch = gmailPatt.test(email.value);
if (emailMatch == false || emailMatch == true) {
document.getElementById("emailError").innerHTML =
"<p>" + emailMatch + "</p>";
} else {}
}
<form>
<div class="form-group row">
<div>
<label for="inputEmail" class="col-sm-1">Email:</label>
<input type="text" class="form-control col-sm-1" id="inputEmail" placeholder="username#gmail.com" />
<p id="emailError"></p>
</div>
</div>
<button type="button" onclick="validationCheck()">Check</button>
</form>

Using JavaScript to store user input from a form into an array of records

This is a problem for school. I need to make an array of records to store user input that loops the number of times the user specifies.
1 - The user will enter the number of volunteers (between 5-10). I have that part working.
2 - The input form is suppose to display the number of times as the number of volunteers. I'm not sure how to do that.
3 - The user's input is to be stored in an array of records.
4 - A message is to be displayed at the bottom with each volunteer's inputted information.
I'm stuck on number 2 and I'm positive I'll need help with 3 & 4 too.
Any assistance would be greatly appreciated.
You can see the code I've written below and I've included the JS code for both functions that I have working (validateForm() & getNumberOfVolunteers())
function getNumberOfVolunteers() {
var y = document.forms["numberOfVolunteersForm"]["numberOfVolunteers"].value;
if (y == "") {
alert("Number of volunteers must be filled out.");
return false;
}
document.getElementById("numberOfVolunteers1").innerHTML = y;
return false;
}
function validateForm() {
var a = document.forms["inviteForm"]["recipientName"].value;
if (a == "") {
alert("Name must be filled out.");
return false;
}
var b = document.forms["inviteForm"]["organizationName"].value;
if (b == "") {
alert("Organization name must be filled out.");
return false;
}
document.getElementById("recipientName1").textContent = a;
document.getElementById("organizationName1").textContent = b;
return false;
}
<!DOCTYPE html>
<html lang="en-US">
<!--
<head>
<script src="js/getNumberOfVolunteers.js"></script>
</head>
-->
<body>
<header>
</header>
<section id="numOfVolunteers">
<form name="numberOfVolunteersForm" onsubmit="return getNumberOfVolunteers()">
<label for="numberOfVolunteers">Number of volunteers:
</label>
<input type="number" min="5" max="10" value="5" name="numberOfVolunteers" id="numberOfVolunteers" placeholder="Enter the number of volunteers" />
<input type="submit" value="submit" id="submit1" />
</form>
</section>
<section id="pageForm">
<form action="#" name=inviteForm onsubmit="return getVolunteerInfoIntoArray()">
Number of Volunteers Entered: <strong><span id="numberOfVolunteers1"> </span></strong> <br/> <br/>
<label for="recipientName">Recipient name:
</label>
<input type="text" name="recipientName" id="recipientName" placeholder="Enter your Recipient Name" />
<label for="organizationName">Organization name:
</label>
<input type="text" name="organizationName" id="organizationName" placeholder="Enter your Organization Name" />
<input type="submit" value="submit" id="submit2" onclick="validateForm" />
</form>
</section>
<article id="placeholderContent">
Hello <span id="recipientName1"></span>!
<br/>
<br/> You have been invited to volunteer for an event held by <span id="organizationName1"></span>
</article>
<script>
var volunteerArray = [];
function getVolunteerInfoIntoArray() {
var volCount;
for (volCount = 5; volCount < getNumberOfVolunteers1.length; volCount++);
document.getElementById('recipientName');
document.getElementById('organizationName');
volunteerArray.push([recipientName.value, organizationName.value]);
}
</script>
</body>
</html>
I need to display the input form and the article multiple times. And store all the input in an array.
Is this what you're trying to do? Hope this helps even it's not exactly what you want hahahah
<!DOCTYPE html>
<html lang="en-US">
<head>
<style>
.numberofvolunteers,
.all-volunteers{
padding:10px;
}
input,button{
margin:3px;
}
span{
font-size:12px;
padding:10px 10px;
}
</style>
</head>
<body>
<div class="numberofvolunteers">
<input type="number" id="volunteers" placeholder="Enter No. of volunteers"><button onclick="createVolunteerForm()">Submit</button>
</div>
<div id="all-volunteers">
</div>
<span id="array"></span>
<script>
var volunteerArray = [];
function createVolunteerForm(){
volunteerArray = [];
var numberofvolunteers = document.getElementById("volunteers").value;
var content = "";
if(parseInt(numberofvolunteers) < 5 || parseInt(numberofvolunteers) > 10){
alert("No. of volunteer should be 5 to 10");
}
else{
for(var i = 0; i < parseInt(numberofvolunteers); i++){
content += createForm(i);
}
}
document.getElementById("all-volunteers").innerHTML = content;
}
function createForm(index){
var content = ' <div id="volunteer-div-'+index+'">'+
'<div id="volunteer-form-'+index+'">'+
'<input type="text" id=recipient-'+index+' placeholder="Enter recipient name">'+
'<input type="text" id=organization-'+index+' placeholder="Enter organization name">'+
'<button id="submit-'+index+'" onclick="displayMessage('+index+');addToArray('+index+');">submit</button>'+
'</div>'+
'<span id="message-'+index+'"></span>'+
'</div>';
return content;
}
function displayMessage(index){
var message = "Hello " + document.getElementById("recipient-"+index).value + " your organization is " + document.getElementById("organization-"+index).value;
document.getElementById("message-" + index).innerHTML = message;
}
function addToArray(index){
volunteerArray.push({recipient : document.getElementById("recipient-"+index).value , organization : document.getElementById("organization-"+index).value});
document.getElementById("array").innerHTML = JSON.stringify(volunteerArray);
}
</script>
</body>
</html>

My JS worked before and now it doesnt

I wanted to make a communication form and I literally copy pasted the code of a previously working one. The only changes I have made to the code are the text parts and CSS. All the name and ids are the same including the form. As I previously stated, literally a copy paste. I checked the console tab, no errors at all. At this point I'm confused. Any help is appreciated.
Code:
<DOCTYPE html>
<html>
<head>
<link REL="STYLESHEET" TYPE="TEXT/CSS" HREF="STYLES.css">
<title>ΣΕΛΙΔΑ ΕΠΙΚΟΙΝΩΝΙΑΣ</title>
</head>
<body>
<form name="CForm" id="CForm" method="post">
<h3>ΦΟΡΜΑ ΕΠΙΚΟΙΝΩΝΙΑΣ</h3>
<form name="myForm" id="form1" onsubmit="return validateForm()" method="post">
<label for="fname">ΟΝΟΜΑ ΚΑΙ ΕΠΩΝΥΜΟ </label>
<input type="text" id="fname" name="fname" placeholder="Ονομα&Επωνυμο" class="otherCFcss">
<label for="tel">ΤΗΛΕΦΩΝΟ</label>
<input type="text" id="tel" name="tel" placeholder="Τηλεφωνο.." class="otherCFcss">
<label for="lname">Email</label>
<input type="email" id="email" name="email" placeholder="something#something.com"><br>
<label for="subject">ΘΕΜΑ</label>
<textarea id="message" name="message" placeholder="Γραψε κατι.." style="height:200px" class="otherCFcss"></textarea>
<input type="submit" id="submitbutton" value="ΑΠΟΣΤΟΛΗ">
<input type="reset" id="resetbutton" value="ΑΚΥΡΩΣΗ">
</form>
</body>
</html>
<script>
var a = sessionStorage.getItem("a");
var b = sessionStorage.getItem("b");
var c = sessionStorage.getItem("c");
var d = sessionStorage.getItem("d");
document.getElementById("fname").value= a;
document.getElementById("tel").value= b;
document.getElementById("email").value= c;
document.getElementById("message").value= d;
function send() {
window.location.href = "mailto:dimtrispap1999#gmail.com?subject=Αυτόματο μήνυμα &body="+"Όνοματεπωνυμο: "+ a +"%0A"+"Τηλέφωνο:"+" "+ b +"%0A"+"Αίτημα,ερωτημα: "+d;
}
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
var y = document.forms["myForm"]["tel"].value;
var z = document.forms["myForm"]["email"].value;
var e = document.forms["myForm"]["message"].value;
if (x == "" || y == "" || z == "" || e == ""){
alert("Fill in the blanks");
} else {
var confirmwindow = window.open("", "_black", "width=560,height=190");
confirmwindow.document.writeln("<h3>Σιγουρα θελετε να στειλετε την παρακατω φορμα?</h3>");
confirmwindow.document.write("<b>Name*: </b>" + x + "<br>");
confirmwindow.document.writeln("<b>Τηλεφωνο*: </b>" + y + "<br>");
confirmwindow.document.writeln("<b>Email*: </b>" + z + "<br>");
confirmwindow.document.writeln("<b>Message*: </b><br>" + e + "<br><br>");
confirmwindow.document.write("<input type='submit' onclick='opener.send()' id='submitbutton' value='ΑΠΟΣΤΟΛΗ'>"+ " ");
confirmwindow.document.writeln("<input type='button' onclick='window.close();' id='resetbutton' value='cancel'>");
}
return false;
}
</script>
I also tried to add a variable outside the functions in both the previous and the current code.Something like that var x=document.forms["myForm"]["fname"].value;.In the previous code (the working one) there were no errors.
In the current one I get from the console this error:
Uncaught TypeError: Cannot read property 'fname' of undefined at
elidaepikoinwnias.html:35.
Line 35 is the line where I add the variable.Once I remove it the error is gone but still the JS code doesn't work.
Looks like you have a redundant and unclosed form - cForm
Remove this line
<form name="CForm" id="CForm" method="post">
You should not be nesting forms, check this

how to validate the post action method in javascript

im using javascript function for simple client side validation
`function IsCodeEmpty() {
if (document.getElementById('InputCode').value == "") {
return 'Patient Code should not be empty';
}
else { return ""; }
}
function IsVisitNoInValid() {
if (document.getElementById('VisitNo').value== "") {
return 'Visit No should not be empty';
}
else { return ""; }
}
function IsValid() {
var CodeValidationMessage = IsCodeEmpty();
var IsVisitNoInValidMessage = IsVisitNoInValid();
var FinalErrorMessage = "Errors:";
if (PatientCodeValidationMessage != "")
FinalErrorMessage += "\n" + CodeValidationMessage;
if (IsVisitNoInValidMessage != ""
FinalErrorMessage += "\n" + IsVisitNoInValidMessage;
if (FinalErrorMessage != "Errors:") {
alert(FinalErrorMessage);
return false;
}
else {
return true;
}
}`
and my view is `
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>AddPatient</title>
<link href="#Url.Content("~/Content/add.css")" rel="stylesheet" type="text/css" />
<script src="~/Scripts/Validation.js"></script>
</head>
<body>
<div class="form-group">
<form action="~/Main/Screen" method="post">
<div class="panel panel-primary">
<div class="panel-heading">TEST ORDER FOR PATIENT</div>
<div class="panel-body">
<h3><label class="control-label"> CODE<span class="inp">*</span></label></h3><input type="text" id="InputCode" name="InputCode" value="" style="height:30px;" /><br />
<h3><label class="control-label">VISIT NO<span class="inp">*</span></label></h3><input type="text" id="visitno" name="VisitNo" value="" style="height:30px;" /><br />
<br />
<button class="btn btn-primary" id="add" type="submit" onclick="return IsValid()";>ADD</button>
</div>
</div>
</form>`
and why i cant get my validation message. it doesnt show any validation message.
i added scripts link on my head section in view. then why iam not getting run javascript
The right bracket of the 4-th if condition statement is missed.
The visitno is not equals to VisitNo. You need to replace visitno identificator with VisitNo in your HTML or replace VisitNo with visitno in javascript .
See working code below.
function IsCodeEmpty() {
if (document.getElementById('InputCode').value == "") {
return 'Patient Code should not be empty';
} else {
return "";
}
}
function IsVisitNoInValid() {
if (document.getElementById('VisitNo').value == "") {
return 'Visit No should not be empty';
} else {
return "";
}
}
function IsValid() {
var CodeValidationMessage = IsCodeEmpty();
var IsVisitNoInValidMessage = IsVisitNoInValid();
var FinalErrorMessage = "Errors:";
if (CodeValidationMessage != "") FinalErrorMessage += "\n" + CodeValidationMessage;
if (IsVisitNoInValidMessage != "") FinalErrorMessage += "\n" + IsVisitNoInValidMessage;
if (FinalErrorMessage != "Errors:") {
alert(FinalErrorMessage);
return false;
} else {
return true;
}
}
<form action="#" method="post">
<div class="panel panel-primary">
<div class="panel-heading">TEST ORDER FOR PATIENT</div>
<div class="panel-body">
<h3><label class="control-label"> CODE<span class="inp">*</span></label></h3><input type="text" id="InputCode" name="InputCode" value="" style="height:30px;" /><br />
<h3><label class="control-label">VISIT NO<span class="inp">*</span></label></h3><input type="text" id="VisitNo" name="VisitNo" value="" style="height:30px;" /><br />
<br />
<button class="btn btn-primary" id="add" type="submit" onclick="return IsValid()" ;>ADD</button>
</div>
</div>
</form>

onsubmit="function()" is not working

I want to validate the dynamically added fields of the form(present in the templates/appname) in django. I am adding those fields with the help of the javascript (addInput.js - stored at a place mentioned as source in the script tag) which also has the logics for removing those fields as well as validating those fields values. But when I click send_invites button, it directs me again to app/register when I first want that it should go to the validateEmail() function if everything is fine then it should redirect to app/register.
var counter = 1;
var limit = 5;
function addInput(divName) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " Email Addresses");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<p id = 'remove" + counter + "'>Email Address " + (counter + 1) + " : " + "<input type = 'text' name ='myInputs[]'></p>";
document.getElementById(divName).appendChild(newdiv);
counter++;
alert(counter + "add");
}
}
function removeInput(divName) {
if (counter == 1) {
alert("You have reached the limit of removing Email Addresses");
} else {
counter--;
var olddiv = document.getElementById("remove" + counter);
alert(counter + "remove");
olddiv.parentNode.removeChild(olddiv);
}
}
function validateEmail(divName) {
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-]+.)+([a-zA-Z0-9]{2,4})+$/;
console.log("cmn");
alert("cmn");
for (i = 0; i < counter; i++) {
var email = $("#remove" + i).val();
alert(email);
// return true;
}
return true;
}
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<br>
<h1 class="page-header">
Send Invites
</h1>
<form method="POST" onsubmit="return validateEmail('dynamicInput')" action="/app/register/">
<div id="dynamicInput">
<p id='remove0'>Email Address 1 :
<input type="text" name="myInputs[]">
</p>
</div>
<br>
<br>
<input type="button" value="Add another Email Address" onClick="addInput('dynamicInput');">
<input type="button" value="Remove Email Address Field " onClick="removeInput('dynamicInput');">
<br>
<br>
<input type="submit" value="Send Invites">
<input type='hidden' name='csrfmiddlewaretoken' value='xyz' />
</form>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
</div>
<!-- /#page-wrapper -->
</div>
<!-- /#wrapper -->
</div>
<style>
a.active {
background-color: #eee;
}
</style>
But why is this not happening? other two javascript functions addInput and removeInput are working fine. Only validateEmail is not getting called, for which I am even calling alert and console.log but nothing is getting displayed. Please help. I am new to javascript.
Running the code, clicking the button, you get the following error in the console.
Uncaught SyntaxError: Invalid regular expression:
/^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-]+.)+([a-zA-Z0-9]{2,4})+$/:
Unterminated group
Looking at the code you have an extra (
/^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-]+.)+([a-zA-Z0-9]{2,4})+$/;
^
So you are either missing a closing ) or you have the extra (. My guess is you are missing a ) before the +. Look at wherever you found the reg exp and see what it should be.

Categories