How to pass input variable from HTML Form - javascript

I'm trying to create a code which will take ask the user how many items of X, Y, etc and use Javascript to calculate the total owed and also to print a summary (receipt) of all items purchased. Sorry for noob question, trying to learn code without any formal training. Thanks for all of the help!
<html>
<head>
<title>Cost Calculator</title>
<script language="javascript" type="text/javascript">
function packageTotal(){
//Enter in prices here
var applePrice = 1;
var bookPrice = 2;
x = Number(document.calculator.books.value);
y = Number(document.calculator.apples.value);
var b = applePrice*x + bookPrice*y;
var p = applePrice*x + bookPrice*y + .5;
if (document.getElementById('noBag').checked) {
//Basic package is checked
document.calculator.total.value = b;
} else if (document.getElementById('yesBag').checked) {
//Pro package is checked
document.calculator.total.value = p;
}
//Want to add summary of purchase
//document.write("You want " + x " books and " y " apples.");
}
</head>
<body>
<!-- Opening a HTML Form. -->
<form name="calculator">
<!-- Here user will enter the number of Books and Apples -->
Enter Number of Books: <input type="text" name="books">
<br />
Enter the Number of Apples: <input type="text" name="apples">
<br />
<br />
<input type="radio" name="item" id="noBag" value="No" /> noBag
<input type="radio" name="item" id="yesBag" value="Yes" checked /> yesBag
<!-- Here result will be displayed. -->
<input type="button" value="Submit" onclick="packageTotal();">
Your Total Price is: <input type="text" name="total">
</form>
</body>
</html>

It's not clear from the question, but if this is the problem:
//Want to add summary of purchase
//document.write("You want " + x " books and " y " apples.");
then that would certainly break. document.write only adds to the current document when the document is still loading. If you call it afterwards it will implicitly open a new document to write to, destroying the current page. Generally document.write is a bad thing.
(also there are trivial syntax errors due to missing + concatenation operators)
If you want to write arbitrary text to the page, create a placeholder element:
<div id="message"></div>
and then set its text content:
function setTextContent(element, text) {
element.innerHTML = ''; // remove current content
element.appendChild(document.createTextNode(text));
}
var message = document.getElementById('message');
setTextContent(message, 'You want '+x+' books and '+y+' apples.');
(There is a textContent property on elements which you can also use instead of the function, but it's not supported on IE<9 which use innerText instead. Simply writing the message directly to innerHTML would also work in this case, but it is a bad habit because it leads to HTML-injection security holes when used with user input.)

Related

Passing variables between pages using localStorage and passing variables in a link

I am learning js, recently, I apologize for my English and for the obviousness of my questions. I have two problems, I would appreciate solutions in pure JavaScript.
Following several tutorials, I installed a localStorage script in an HTML page.
pag1.html
<p> Hello! what's your name?</p>
<form action="pag2.html">
<input type="text" id="txt"/>
<input type="submit" value="nome" onClick="passvalues();"/>
</form>
// the form has a link to pag2.html
<script>
function passvalues()
{
var nme=document.getElementById("txt").value;
localStorage.setItem("textvalue",nme);
return false;
}
</script>
Let's say the user enters the name "Lucy":
pag2.html
<p>Hi <span id="result">Lucy<span> nice to meet you!</p>` // the name appears
<p>How are you today <span id="result">NOTHING</span>?</p>` // the name does not appear
pag3
<script>
document.getElementById("result").innerHTML = localStorage.getItem("textvalue");
</script>
First Question
the NAME appears only once for my mistake or must it be so? Should I use another syntax to make it appear several times?
pag3.html
<p><span id="result">Lucy</span>which gender designation do you prefer to be used with you?</p>
<p>male</p>
<p>female</p>
<p>neutral</p>
<script>
document.getElementById("result").innerHTML = localStorage.getItem("textvalue");
</script>
Second Question
In pag 3 the user has to choose whether he wants to be called male, female or neutral.
One solution is to set three different pages according to the genre chosen. But this solution is not elegant and inflates the number of pages.
I seem to have read somewhere that with js it is possible to go to another page and at the same time set the value of a Boolean variable (true / false) through a link.
Something like this (the syntax is invented):
<a href="female.html" set var f true> female</a>
This would allow you to create a single landing page with the insertion of three "if":
if (female true) {
text = "brava";
} else if (male true) {
text= "bravo";
} else {
text = "bene";
}
Is it possible to do this? How?
I have tried this script htmlgoodies several times but it is too difficult for me.
Hello,
First of all I'd thank #cssyphus and #Shahnawazh for the answers.
Question 1
I managed to show the name several times on the same page with the script:
<script>
var result = document.getElementsByClassName('result');
[].slice.call(result).forEach(function (className) {
className.innerHTML = localStorage.getItem("textvalue");
});
</script>
But, do I really need to include it on all pages that need to show the name?
I also tried to insert the script into an external js page but the name did not appear even once.
Question 2
As for the second question, I did not get positive results.
Rather than using id, you can use class for showing result because id is unique. Also for storing male, female or neutral you can use radio buttons, and when you click any of them, just save the result in the localStorage. Here are the three pages.
page1.html
<body>
<p> Hello! what's your name?</p>
<form action="page2.html">
<input type="text" id="txt" />
<input type="submit" value="name" onClick="passvalues();" />
</form>
<script>
function passvalues() {
var nme = document.getElementById("txt").value;
localStorage.setItem("textvalue", nme);
return false;
}
</script>
</body>
page2.html
<body>
enter code here
<p>Hi <span class="result">Lucy<span> nice to meet you!</p>
<p>How are you today <span class="result"></span>?</p>
page3
<script>
var result = document.getElementsByClassName('result');
[].slice.call(result).forEach(function (className) {
className.innerHTML = localStorage.getItem("textvalue");
});
</script>
</body>
page3.html
<body>
<p><span class="result"></span> which gender designation do you prefer to be used with you?</p>
<form name="genderForm" action="">
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="neutral"> Neutral
</form>
<p>You've selected <span class="selectedGender"></span></p>
<script>
var result = document.getElementsByClassName('result');
[].slice.call(result).forEach(function (className) {
className.innerHTML = localStorage.getItem("textvalue");
});
var rad = document.genderForm.gender;
var prev = null;
for (var i = 0; i < rad.length; i++) {
rad[i].addEventListener('change', function () {
(prev) ? console.log(prev.value) : null;
if (this !== prev) {
prev = this;
}
console.log(this.value);
document.getElementsByClassName("selectedGender")[0].innerHTML = this.value;
localStorage.setItem("gender", this.value);
});
}
</script>
</body>
You have just discovered why you cannot have two elements on the same page with the same ID - only the first one will work. However, classes work almost exactly like IDs, so just use the same className at both locations:
<p>Hi <span class="result">Lucy<span> ...
...
<p>How are you today <span class="result">Lucy</span> ...
As to your second problem, just use localStorage again. Set a different localStorage variable and read/write that.
However, what you are probably thinking of is using a query string, like this:
female
See this SO question for information and code examples.

Prevent Wrong Input in JS After Submitting A Form

I am creating a sample MabLibs type thing in HTML and JS. When the person inputs stuff in a field, it will use that to create their own MadLib.
I've done a little research and not finding exactly what I am looking for. Say a person puts 12 in the Name field. How would code that so if this instance does happen, it won't go through and alert "That is not a valid input. PLease type again!" or something along those lines.
The code I am using is below. I am very new to Javascript so I know the format and stuff might be wrong.
<html><head>
<title>
Mad Libs Story
</title>
<script>
function getVars() {
person1 = String(document.getElementById("personOne").value);
age = Number(document.getElementById("ageOne").value);
firstAdjective = String(document.getElementById("adjective").value);
document.getElementById("madLibCreation").innerHTML = "There once was a person named " + person1 + ". She was " + age + " and very " + firstAdjective = ".";
}
</script>
</head>
<body>
<h3>
Welcome to Mad Libs! Please type in the prompted Information. Then press the submit button. Have fun!
</h3>
<p>
Name of Person in Room: <input type="text" id="personOne">
</p>
<p>
Age: <input type="text" id="ageOne">
</p>
<p>
Adjective: <input type="text" id="adjective">
</p>
<input type="submit" value="Get My MadLib Creation!" onclick="getVars();">
<p id="madLibCreation"></p>
</body></html>
For that, you have to check Name field value is number or not. We can check the value is number or not using isNaN function. This function returns true or false.
isNaN(12) // falsee
isNaN(-4.5) // false
isNaN(15-3) // false
isNaN(0) // false
isNaN('123') // false
isNaN('Nuwan') // true
isNaN('2005/12/12') // true
isNaN() // true
So, in your code getVars() function change like this
function getVars() {
var name = document.getElementById("personOne").value;
if(!isNaN(name) && name.length != 0){
alert("That is not a valid input. PLease type again!");
}else{
person1 = String(document.getElementById("personOne").value);
age = Number(document.getElementById("ageOne").value);
firstAdjective = String(document.getElementById("adjective").value);
document.getElementById("madLibCreation").innerHTML = "There once was a person named " + person1 + ". She was " + age + " and very " + firstAdjective + ".";
}
}
https://www.w3.org/WAI/tutorials/forms/validation/
This link provides some useful information and example code around how you can do this with HTML5, providing the validations and required inputs to each input field.
By implementing these validations your form will not submit until the requirements are met.
Here are a few other ideas that may also help:
By using a
<form onsubmit="getVars()" name="MadLibs">
tag, your data will be wrapped inside the event, which can be accessed within your submit function. This will also reduce the effort to collect the data via element id’s.
const getVars = function(event) {
event.preventDefault(); // stop the page refresh on submit
const formData = event.target;
const personOne = formData.personOne;
...
}
Lastly by adding tags for each input, it will further increase the accessibility of the form:
https://www.w3.org/WAI/tutorials/forms/labels/
Hope this helps with your project.
So you want to prevent wrong information before submitting any thing. This can be achieved by some checks to the value entered into the fields. This can be done all at once on button click or while typing with an event handler on the field for keyup. You can further use setTimeout to check with a small delay.
If you check and set classes to elements which are faulty, you can check for them with a css selector.
const person1 = document.getElementById("personOne")
const age = document.getElementById("ageOne")
const firstAdjective = document.getElementById("adjective")
// use a function(){} block for the handler, it will bin this
person1.addEventListener(`keyup`, function(){
// use arrow function to not bind this so it will refer to the html node
// can be used to delay the evaluation
setTimeout(()=>{
// some regex... /regex/flags will create a new regex
// ^ is start, $ is end and [a-z]* is a to z 0 or more times
// flag i is case insensitive
const regEx = /^[a-z]+$/i
//
if(!regEx.test(person1.value)){
this.classList.add(`invalid`)
} else {
this.classList.remove(`invalid`)
}
},200)
})
function getVars() {
if(!document.querySelectorAll(`.invalid`)[0]){
document.getElementById("madLibCreation").innerText = `There once was a person named ${person1.value} she was ${age.value} and very ${firstAdjective.value}.`
} else {
alert(`fix your shit`)
}
}
.invalid{
color: red;
}
<html>
<head>
<title>
Mad Libs Story
</title>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' media='screen' href='main.css'>
</head>
<body>
<h3>
Welcome to Mad Libs! Please type in the prompted Information. Then press the submit button. Have fun!
</h3>
<p>
Name of Person in Room: <input type="text" id="personOne">
</p>
<p>
Age: <input type="text" id="ageOne">
</p>
<p>
Adjective: <input type="text" id="adjective">
</p>
<input type="submit" value="Get My MadLib Creation!" onclick="getVars()">
<p id="madLibCreation"></p>
</body>
<script src="./main.js"></script>
</html>

How to print random string from a selection of user form inputs javascript/jquery

var textEntered = function() {
var input = document.userNameForm.userInput.value;
if(input) {
document.getElementById("resultText").innerHTML += input + "<br>";
}
}
This is what I have so far and this obviously just prints out the user inputs onto the screen in a list. But I want to somehow store all these user inputs from the form I have in my HTML, (maybe in an array?) and maybe assign each to a number and use Math.floor(Math.random()) to print out a random result. (I'm just making a little/random site where you put in the names of your friends and it returns and prints a random name from the names that you give it, if that makes sense).
I'm a beginner just so you know
function textEntered() {
var inputs = [];
$('form input').each((i,e)=>inputs.push(e.value));
if (inputs) {
document.getElementById("resultText").innerHTML += inputs[Math.floor(Math.random()*inputs.length)] + "<br>";
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input value="Hello">
<input value="World">
<input value="from Stardust">
<button onclick="textEntered()">Submit Now!</button>
</form>
<div id="resultText">Submit it!
<br><br>
</div>
Is this essentially what you are looking for?

Dynamic values in object properties

want to make values of the oject's dynamic (from user input) but I get "undefined". The idea is to have 3 input fields and the user should input values in them which will fill up the alert message.
<script type="text/javascript">
function Family (fatherName, motherName, sisterName) {
this.fatherName = fatherName;
this.motherName = motherName;
this.sisterName = sisterName;
this.myFamily = function() {
alert("My father's name is " + this.fatherName +", my mother's name is "+ this.motherName +" and my sister's name is " + this.sisterName +".");
}
}
var Me = new Family(
Family["fatherName"] = father,
Family["motherName"] = mother,
Family["sisterName"] = siter);
var father = document.getElementById("fatherId").value;
var mother = document.getElementById("motherId").value;
var sister = document.getElementById("sisterId").value;
</script>
<input type="text" id="fatherId" />
<input type="text" id="motherId" />
<input type="text" id="fatherId" />
<input type="submit" value="Send" onclick="Me.myFamily();">
Also I'm looking for a way how user can add or remove properties (values in them, too).
There are a few things wrong with your code.
You've used your variables here
Family["fatherName"] = father,
Family["motherName"] = mother,
Family["sisterName"] = siter); // This should be sister by the way
before declaring them here
var father = document.getElementById("fatherId").value;
var mother = document.getElementById("motherId").value;
var sister = document.getElementById("sisterId").value; // Doesn't exist
Try switching the statements so you're declaring the variables first.
Also, there is no sisterId, you've used fatherId twice.
You're also calling javascript before the DOM is ready. If you're using jQuery, wrap your JS in
$(document).ready(function() { }
or if you want to stick with plain JS, try
window.onload = function() { }
You'll have to be more specific on what myFamily is supposed to do, since you haven't even mentioned that method.
Here is the working snippet of your example.
<input type="text" id="fatherId" />
<input type="text" id="motherId" />
<input type="text" id="sisterId" />
<input type="submit" value="Send" id="submit" />
<script>
function Family(fatherName, motherName, sisterName) {
this.fatherName = fatherName;
this.motherName = motherName;
this.sisterName = sisterName;
this.myFamily = function() {
alert("My father's name is " + this.fatherName +
", my mother's name is " + this.motherName +
" and my sister's name is " + this.sisterName + ".");
};
}
document.getElementById("submit").onclick = function() {
var father = document.getElementById("fatherId").value;
var mother = document.getElementById("motherId").value;
var sister = document.getElementById("sisterId").value;
Me = new Family(father, mother, sister);
Me.myFamily();
}
</script>
All the mistakes are summarized very well by Brandon.
*EDIT: (anser to your comment)
Your code has two execution related problems.
<script> tags are executed immediately and therefore if you insert script before the <input> part then there are no input elements available for you to retrieve.
You want to retrieve values of the inputs, but those inputs contain data when user clicks on the submit and therefore must be read using .value() at the onclick time. If you try to read them outside the onclick part then they are accessed immediately during page load when the input fields are empty.

how do i get the info from a form using javascript?

i have a form which user enters some data, could be checkboxes, radio buttons, textfields, etc
when user click submit button, i want to refresh the page with whatever data that was entered
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
</head>
<body id="ref">
<form>
Please enter your name:<input type="text" id="name" />
Please enter your age:<input type="text" id="age" />
</form>
<input type="button" onclick="c()" value="submit">
<script type="text/javascript">
function c()
{
var o = document.getElementById('ref');
o.innerHTML = '';
var n = document.createElement('p');
var nam = document.getElementById('name');
n.innerHTML = "Your name is: " + nam;
o.appendChild(n);
var a = document.createElement('p');
var ag = document.getElementById('age');
a.innerHTML = "Your age is: " + ag;
o.appendChild(a);
//how do i get the info from the form? because both nam and ag are coming up null
}
</script>
</body>
</html>
my guess this is not working is because the page refreshes then tries to fetch the element by id which is not there anymore.. whats the correct way of doing this??
You're confusing objects with their properties. Here, you're getting the HTMLInputElement instance for the "age" field:
var ag = document.getElementById('age');
But here you're using that object as though it were a simple value:
a.innerHTML = "Your age is: " + ag;
The HTMLInputElement object has a value field you can use for that:
a.innerHTML = "Your age is: " + ag.value;
Separately, you're completely destroying the page by doing this:
var o = document.getElementById('ref');
o.innerHTML = '';
...because you've given the body element the ID "ref". Completely replacing the body element completely replaces the body element, so you can't rely on objects that only exist as subordinates of that element.
The usual thing is to have an element to fill in, and (optionally) to remove the elements you no longer need. For instance (live copy):
HTML:
<form id="theForm">
Please enter your name:<input type="text" id="name" />
Please enter your age:<input type="text" id="age" />
<input type="button" onclick="c()" value="submit">
</form>
<div id="result">
</div>
(Note I moved the button into the form for convenience.)
JavaScript:
function c() {
var form = document.getElementById("theForm"),
nameField = document.getElementById("name"),
ageField = document.getElementById("age"),
result = document.getElementById("result");
form.parentNode.removeChild(form);
result.innerHTML =
"Your name is " + nameField.value +
" and your age is " + ageField.value;
}
There, when the button is pressed, I remove the form and fill in the "result" div.
You could add the "result" div dynamically if you wanted (live copy):
HTML:
<form id="theForm">
Please enter your name:<input type="text" id="name" />
Please enter your age:<input type="text" id="age" />
<input type="button" onclick="c()" value="submit">
</form>
JavaScript:
function c() {
var form = document.getElementById("theForm"),
nameField = document.getElementById("name"),
ageField = document.getElementById("age"),
result;
result = document.createElement("div");
result.innerHTML =
"Your name is " + nameField.value +
" and your age is " + ageField.value;
form.parentNode.insertBefore(result, form);
form.parentNode.removeChild(form);
}
You can access the fields using a briefer and somewhat more natural syntax if you change your id values to name values instead (live copy):
HTML:
<form name="theForm">
Please enter your name:<input type="text" name="name" />
Please enter your age:<input type="text" name="age" />
<input type="button" onclick="c()" value="submit">
</form>
JavaScript:
function c() {
var form = document.theForm,
nameField = form.name,
ageField = form.age,
result;
result = document.createElement("div");
result.innerHTML =
"Your name is " + nameField.value +
" and your age is " + ageField.value;
form.parentNode.insertBefore(result, form);
form.parentNode.removeChild(form);
}
Further reading:
DOM2 Core (well-supported by most modern browsers)
DOM2 HTML
DOM3 Core (increasingly supported)
If you want to update your html using java-script only , you may use ".value" attribute of the input;
var a = document.createElement('p').value;
var ag = document.getElementById('age').value;
Usually the Form information is processed using server-side code , this is done by specifying the action attribute of the form:
<form action="processuserinfo.aspx">
...
</form>
I'm pretty sure this isn't doable javascript alone. You'll need to use a server-side language like php. Try to google php forms, and you should get some good results. :)

Categories