My JS worked before and now it doesnt - javascript

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

Related

Trying to get cookies to prepopulate fields in a form in html

Hi I am new to software development and working on code. I am trying to get cookies to populate a field in my form when a user has input into it previously. However not able to work it out.
I have tried to setcookies and getcookies to work , however just cannot populate the form value for some reason. I am getting undefined in the field.
<script>
var today = new Date();
var expiry = new Date(today.getTime() + 30 * 24 * 3600 * 1000); // plus 30 days
function setCookie(name, value) {
document.cookie = name + "=" + escape(value) + "; path=/; expires=" +
expiry.toGMTString();
}
</script>
<script>
function storeValues(form) {
setCookie("phoneNumber", form.phoneNumber.value);
return true;
}
</script>
<script type="text/javascript">
function getCookie(name) {
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
</script>
<body>
<form name="contactInfo" id="contactInfo" autocomplete="on" action="/javascript/getcookie/" onsubmit="storeValues(this)">
<fieldset>
<legend>How can we reach you ?</legend>
<div>
<label style="width: 40%;" for="phoneNumber">What number can we call
you on ? <font color="red">*</font> </label>
<input name="phoneNumber" type="tel" id="phoneNumber" placeholder="e.g. 0412345678" onfocus="this.placeholder=''" onblur="this.placeholder='e.g. 0412345678' ; validatePhoneNumber(this)" required>
<input type="submit" class="submit" id="post-btn" value="Call Me" />
</form>
<script>
document.getElementById("phoneNumber").value = document.write(getCookie("phoneNumber"));
</script>
</body>
I am expecting to get the number that i previously entered into the form to populate the next time I load the page.
Try to use the sessionStorage instead of cookiee .
It saves a lot of coding hack.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<body onLoad="getSession()">
<form >
<fieldset>
<legend>How can we reach you ?</legend>
<div>
<label style="width: 40%;" for="phoneNumber">What number can we call
you on ? <font color="red">*</font> </label>
<input name="phoneNumber" type="tel" id="phoneNumber" placeholder="e.g. 0412345678" required>
<!-- <button onClick="validatePhoneNumber(this)">Submit</button> -->
<input type="submit" class="submit" id="post-btn" value="Call Me" onClick="validatePhoneNumber(this)"/>
</form>
</body>
</html>
<script>
function validatePhoneNumber(){
var value = document.getElementById("phoneNumber").value;
console.log(value)
sessionStorage.setItem("phoneNumber", value);
}
function getSession(){
console.log("hey");
var session = sessionStorage.getItem("phoneNumber");
document.getElementById("phoneNumber").setAttribute("value" , session);
}
</script>
Notice :- Removed some attribute and field because i am not having that data , you can add according to your necessity .
For more detail about sessionStorage , visit LINK

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>

This calculator using form submission to satisfy variables isn't working

I am attempting to make a calculator in order to... well, calculate something. Anyway, I am trying to make 4 variables be set too 4 user inputs by using form submission. However, no matter what I do, I can't get the variables to get set. Help would be appreciated!
<!DOCTYPEhtml>
<html>
<head>
<title>NatHisCalc</title>
</head>
<body>
<h1><center><b><p>Test</p></b></center></h1>
<center><b><p id='output'>loading...</p></b></center>
<center><b><p id='output2'>loading...</p></b></center>
<center><b><p id='output3'>loading...</p></b></center>
<center><b><p id='output4'>loading...</p></b></center>
<form id="a" action="/action_page.php">
Input X <input type="number" name="x"><br><br>
<input type="button" onclick="calc()" value="Submit">
</form>
<form id="a" action="/action_page.php">
Input X <input type="number" name="y"><br><br>
<input type="button" onclick="calc()" value="Submit">
</form>
<form id="a" action="/action_page.php">
Input X <input type="number" name="a"><br><br>
<input type="button" onclick="calc()" value="Submit">
</form>
<form id="a" action="/action_page.php">
Input X <input type="number" name="b"><br><br>
<input type="button" onclick="calc()" value="Submit">
</form>
<script>
function calc() {
var x = document.getElementById("x").submit();
var y = document.getElementById("y").submit();
var a = document.getElementById("a").submit();
var b = document.getElementById("b").submit();
var u = (0.101*(y/100))*(480000*(a/100))
var j = (0.581*(x/100))*(120000*(b/100))
if (x > 150 || x < 50) {
window.alert('Hold on... Those inputs will result in an unreasonable output. You can click ');
}
var preresult = j + u;
if (preresult < 177000) {
document.getElementById('output').innerHTML = 'Test';
} else {
document.getElementById('output').innerHTML = 'Test1';
}
if (u > 179999) {
document.getElementById('output').innerHTML = 'Test2';
}
document.getElementById('output2').innerHTML = 'Test3' + j;
document.getElementById('output3').innerHTML = 'Test4 ' + u;
document.getElementById('output4').innerHTML = 'Test5 ' + preresult;
}
</script>
</body>
</html>
Looked into your code, it seems that you have made things way too much complicated that it should be. First of all, you don't call submit function on the input to get the value of it. If you want to get the value of x then you just access the value property like this document.getElementById("x").value. Secondly, you really don't need four buttons, all you need to do is ONE button that submits the form and adding required on input fields makes the browser not submit the form until all forms are filled. Last of all, id attribute needs to be unique across your page. You have both form and input field as id a which is unacceptable. It will show no error but get you in sorts of trouble. You can see what I did here, where I prevented the form from being submitted upon the button click and simply called the calc function to perform the calculation.
<!DOCTYPEhtml>
<html>
<head>
<title>NatHisCalc</title>
</head>
<body>
<h1><center><b><p>Test</p></b></center></h1>
<center><b><p id='output'>loading...</p></b></center>
<center><b><p id='output2'>loading...</p></b></center>
<center><b><p id='output3'>loading...</p></b></center>
<center><b><p id='output4'>loading...</p></b></center>
<form onsubmit="event.preventDefault(); calc();" action="/action_page.php">
Input X <input type="number" id="x" required><br><br>
Input Y <input type="number" id="y" required><br><br>
Input A <input type="number" id="a" required><br><br>
Input B <input type="number" id="b" required><br><br>
<input type="submit" value="Submit">
</form>
<script>
function calc() {
var x = document.getElementById("x").value;
var y = document.getElementById("y").value;
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var u = (0.101*(y/100))*(480000*(a/100))
var j = (0.581*(x/100))*(120000*(b/100))
if (x > 150 || x < 50) {
window.alert('Hold on... Those inputs will result in an unreasonable output. You can click ');
}
var preresult = j + u;
if (preresult < 177000) {
document.getElementById('output').innerHTML = 'Test';
} else {
document.getElementById('output').innerHTML = 'Test1';
}
if (u > 179999) {
document.getElementById('output').innerHTML = 'Test2';
}
document.getElementById('output2').innerHTML = 'Test3' + j;
document.getElementById('output3').innerHTML = 'Test4 ' + u;
document.getElementById('output4').innerHTML = 'Test5 ' + preresult;
}
</script>
</body>
</html>

Derivate in JavaScript

I have this code.
<script src="http://nerdamer.com/js/nerdamer.core.js"></script>
<script src="http://nerdamer.com/js/Algebra.js"></script>
<script src="http://nerdamer.com/js/Calculus.js"></script>
<div id="text"></div>
<form name="formulario" onsubmit="return procesar(this);">
Ingrese la funcion:
<input name="func" type="text" size="15" />
<input type="submit" value="Procesar" />
</form>
JavaScript Code:
//Calculo de derivada
var func = document.getElementsByName("func")[0].value;
var result = nerdamer('diff(2x^3+3x^2)').evaluate();
document.getElementById('text').innerHTML += '<p>'+result.text()+'</p>';
I need that when I introduce manually the function, on input, when I click on ''Procesar'' calculate derivate. Thank you, I dont know how... need help.
I mean, save the value pass to the function and show result.
I don't know that library, but it seems you can differentiate an expression expr with
nerdamer.getCore().Calculus.diff(nerdamer(expr).symbol).text()
It's a bit long, but safer than nerdamer("diff(" + expr + ")") in case expr is malformed.
Then, you can use
document.forms.formulario.addEventListener('submit', function(e) {
e.preventDefault(); // Don't send form
var expr = this.elements.func.value,
diff = nerdamer.getCore().Calculus.diff(nerdamer(expr).symbol).text();
document.getElementById('text').textContent = diff;
});
<script src="http://nerdamer.com/js/nerdamer.core.js"></script>
<script src="http://nerdamer.com/js/Algebra.js"></script>
<script src="http://nerdamer.com/js/Calculus.js"></script>
<form name="formulario">
Enter function:
<input name="func" type="text" size="15" />
<input type="submit" value="Differentiate" />
</form>
<div id="text"></div>
You have to create procesar function :
function procesar(_this){
//Calculo de derivada
var func = document.getElementsByName("func")[0].value;
var result = nerdamer('diff(2x^3+3x^2)').evaluate();
document.getElementById('text').innerHTML += '<p>'+result.text()+'</p>';
return false; //Prevent the refresh
}
Hope this helps.
This shows derivative:
function Differentiate(sender) {
var func = document.getElementsByName("func")[0].value.trim();
var result = nerdamer('diff(' + func + ')').evaluate();
var html = document.getElementById('text').innerHTML;
html = '<p>' + result.text() + '</p>' + html;
document.getElementById('text').innerHTML = html;
}
<script src="http://nerdamer.com/js/nerdamer.core.js"></script>
<script src="http://nerdamer.com/js/Algebra.js"></script>
<script src="http://nerdamer.com/js/Calculus.js"></script>
<form name="formulario" method="get" onsubmit="return Differentiate(this);">
Ingrese la funcion:
<input name="func" type="text" size="15" />
<input type="submit" value="Differentiate" />
</form>
<div id="text"></div>
Unfortunately I am unable to comment under the accepted answer but would like to make a slight modification to it which should achieve the same result. Also keep in mind that if your function contains more than one variable then you need to specify with respect to which variable you're differentiating.
document.forms.formulario.addEventListener('submit', function(e) {
e.preventDefault(); // Don't send form
var value = this.elements.func.value,
deriv = nerdamer('diff('+value+')').text();
document.getElementById('text').textContent = deriv;
});
<script src="http://nerdamer.com/js/nerdamer.core.js"></script>
<script src="http://nerdamer.com/js/Algebra.js"></script>
<script src="http://nerdamer.com/js/Calculus.js"></script>
<form name="formulario">
Ingrese la funcion:
<input name="func" type="text" size="15" />
<input type="submit" value="Procesar" />
</form>
<div id="text"></div>

How can I add values of form textbox using string ,for loop

hi guys i am new to js and html.I need a o/p as when click the button tat should show the all contents entered in form...
My code for giving alert of all entered data in single
how can I add values of form textbox using string ,for loop all should be only in javascript...or else give your own code with the conditions i said....
<html>
<head>
<title>elements in a form</title>
<script type="text/javascript">
function processFormData()
{
var len= document.getElementsByTagName('name');
var str1=null;
for(i=0;i<=len;i++)
{
var str=(subscribe.name[i].value);
str=str1+str;
}
alert(str);
}
</script>
</head>
<body>
<form name ="subscribe" >
<p><label for="name">Your Name: </label><input type="text" name="name" id="txt_name" value="name"></p>
<p><label for="email">Your Email: </label><input type="text" name="email" id="txt_email" value="mail"></p>
<input type="button" value="submit" onclick="processFormData()">
</form>
</body>
</html>
Try that for a start
var len= document.getElementsByTagName('input').length;
// add that you want the number of element
// Change 'name' for 'input' when using 'name' you are looking for <name in the HTML
// if you want the element with the name ABC use getElementsByName()
var str1='';
for(i=0;i<=len;i++)
{
var str=(subscribe[i].value);
str1=str1+str;
}
alert(str1);
jsFiddle example (in jQuery for the calling of the function) : http://jsfiddle.net/DavidLaberge/HPuhg/1/
<html>
<head>
<title>elements in a form</title>
<script type="text/javascript">
var str1=null;
function processFormData()
{
var len= document.getElementsByTagName('name').length;
for(i=0;i<=len;i++)
{
var str=(subscribe.name[i].value);
str1=str1+str;
}
alert(str1);
}
</script>
</head>
<body>
<form name ="subscribe" >
<p><label for="name">Your Name: </label><input type="text" name="name" id="txt_name" value="name"></p>
<p><label for="email">Your Email: </label><input type="text" name="email" id="txt_email" value="mail"></p>
<input type="button" value="submit" onclick="processFormData()">
</form>
</body>
</html>
you have just minor mistake that is you used str in place of str1; Now use the above code.
Try something like:
function processFormData() {
var inputs = document.getElementsByTagName("input"),
i,
len,
stringBuffer = [],
str;
for (i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].type.toLowerCase() === "text") {
stringBuffer.push(inputs[i].value);
}
}
str = stringBuffer.join(""); // str contains concatenated values of all inputs
}
Try this:
function processFormData()
{
var len= document.getElementsByTagName('input').length;
var str = '';
for(i=0;i<len-1;i++)
{
str += document.subscribe[i].value;
}
alert(str);
}

Categories