Nothing happens when trying to submit html form variable via javascript - javascript

I'm a beginner javascript user and I'm trying to get this html form to pass to this javascript function and output the name variable but all that happens when I click the button to submit is that the form input clears and it stays on the form not passing to the javascript.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Life Insurance Calculator</title>
<script type="text/javascript">
var title = "Welcome to Life Insurance Co..!";
//Declaring variable title
document.writeln(title.fontsize(8).fontcolor('red'));
//Printing out the title on the page
function Name(form){
var customername = document.getElementByID("name").value;
document.write(customername);
}
</script>
</head>
<body>
<form name = "LifeCalcForm" action="" method="get">
<p>To get a life insurance quote, please tell us about yourself.</p>
<p><i>Note:only those under the age of 80 and non-smokers may apply</i></p>
<p>Enter your name: <input type="text" name="name" /></p>
<input type="submit" value="Calculate" onClick="Name(this.form)">
</form>
</body>
</html>

When you do document.write(customername); after the page has loaded (specifically, after the load event), it will first clear the entire page (including scripts) and write the new content.
Instead do something like:
alert(customername);
Once you clear the alert (e.g. click "OK"), the form will submit and the page will reload.
Incidentally, since you pass a reference to the function in the call, and the form control has a name, you can use:
alert(form.name.value);
Be aware that form control names and IDs are used to create properties of the form object, so having a form control with a name of "name" overwrites the form's own name property (forms also have properties like submit, action, elements, reset and so on). So never use a control name that might be the same as a standard form property name, use things like "userName" or such.
Variable names are, by convention, reserved for constructor functions so use lower case for normal functions. Also, functions are do things so it's generally best to use a verb that describes what it does, e.g.
function getUserName(form) {
return form.userName.value;
}

Try this:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Life Insurance Calculator</title>
<script type="text/javascript">
var title = "Welcome to Life Insurance Co..!";
// Declaring variable title
document.writeln(title.fontsize(8).fontcolor('red'));
// Printing out the title on the page
function Name(){
var customername = document.getElementById("name").value;
document.write(customername);
}
</script>
</head>
<body>
<form name = "LifeCalcForm" action="" method="get">
<p>To get a life insurance quote, please tell us about yourself.</p>
<p><i>Note:only those under the age of 80 and non-smokers may apply</i></p>
<p>Enter your name: <input type="text" id="name" name="name" /></p>
<input type="button" value="Calculate" onClick="Name()">
</form>
</body>
</html>

Related

constantly updating a button's name

I have code like this, and I want the raise button to tell the user how much they are going to bet if they click the button. If the value of the input were changed to 10, then I want the raise button to say "raise 10". Something along those lines. I'd like it to essentially change in 'real time' as a user types in the input box.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>poker</title>
</head>
<body>
<div>
<form id="actionForm">
<button id="fold" class="turn" type="submit">Fold</button>
<button id="call" class="turn" type="submit">Call</button>
<button id="raise" class="turn" type="submit">Raise<br>0</button>
<br>
<input id="amount" autocomplete="off" title="amount" value="0" />
</form>
</div>
</body>
</html>
I think I worded the question poorly when I searched online so I've come here for help. I'm not sure if I need js to do this with a loop of sorts, or there is something built into HTML.
Try something like this:
<script>
function updateButton()
{
// get value from input field
var inputValue = document.getElementById("inputField").value;
// update button text
document.getElementById("raise").innerHTML = "Raise " + inputValue;
}
</script>
The HTML
<input type="text" id="inputField" oninput="updateButton()">
PS: The oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus, after the content has been changed.
You will need Javascript to create this behavior.
Steps would be :
Save "Raise" value into a variable
Set this value for your "button" label, and use it for increasing the amount
Here's what I came with :
<script>
function handleChange(){
var amount = document.getElementById('amount').value
document.getElementById('raise').innerText = `Raise ${amount}`
}
</script>
and call it as follows :
<input id="amount" autocomplete="off" onkeyup="handleChange()" />
I'm using "onkeyup" to achive the 'real-time' you mentioned.
Hope it helps!

How to create HTML elements and apply them to a different HTML file using Javascript?

I am attempting to create a couple of web pages that will allow me to fill out a form on input.html and have the entered data appended to a different HTML file, index.html.
I have been searching for an answer for a couple of hours now and it might just drive me insane!
Here is some example code of what I'm trying to do:
HTML form input.hmtl:
<form>
<label>
Enter something:
<input type="text" id="userinput" required>
</label>
<input type="submit" id="submit" value="submitted">
</form>
Javascript to get entered data and pass to index.html:
var userInput = document.querySelector("#userinput");
var submit = document.querySelector("#submit");
function addToIndex()
{
// create new element on index.html
}
submit.addEventListener("click", addToIndex, false);
HTML output file index.html:
<div id="contentstart">
<!-- newly created element here -->
</div>
I have attempted using this solution, but Chrome's console gives me an error and tells me that newWindow is not a function. I just stumbled upon using the <iframe> element in a couple of answers but don't quite understand it yet (I'm a noob).
Thanks in advance!
The best option is to use a web server or a serverless implementation. Server code can be written in multiple languages. Some of the languages include PHP, NodeJS, and ASP.NET.
However, you can pass data using browser storage.
But, browser storage is not secure and can be wiped at any time by the user. If you are storing information such as passwords or data that should be visible to multiple users, you should use a web server and/or database.
You need to have a script on both pages. The page with the form will store/set the data. The index page will retrieve the data and use javascript to render more content.
function addToIndex()
{
localStorage.setItem('input', userInput .value)
}
The script for the index page would look something like this.
var data = localStorage.getItem('input');
if (input) {
document.querySelector('#contentstart').innerHTML = data;
}
I put together a simple demo here.
http://plnkr.co/edit/iAitGxtdsHwXowNg
For you to receive data from a form in a different file, you will need a server-side language like php.
So the form will have this structure
<form action="external_file.php" method="get">
<label>
Enter something:
<input type="text" id="userinput" name="user_input" required>
</label>
<input type="submit" id="submit" value="submitted">
</form>
Note the action="external_file.php and the name="user_input" attribute added to the input element.
Then the file: external_file.php might have the following structure to receive the content from the form
<?php
$input = $_GET["user_input"];
//do something with $input
echo 'The data you entered is: ' . $input;
?>
I showed you the way to start. The rest is up to you, you can do whatever you want to do. I hope you could help.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form id ="form">
<label>
Enter something:
<input type="text" id="userinput" required>
</label>
<input type="submit" id="submit" value="submitted">
</form>
<script>
let form = document.getElementById("form");
let userInput = document.getElementById("userinput");
form.addEventListener("submit", submitForm) //this function will work when the form is submit
function submitForm (e) {
e.preventDefault() // this event will prevent page refresh when form submit
let userInputValue = userInput.value; // userinput value
console.log(userInputValue);
moveToAnotherPage(userInputValue); //we send the value we get from userinput to use in another function.
}
function moveToAnotherPage (value) {
// Select the index2 html elements and add with innerhtml or something.
//to do this, you may need to save the userinput value you received to localStorage and pull it from it. I suggest you look into localStorage .And if you know php, you can use it.
}
</script>
</body>
</html>

Reading inputs and printing variables - JavaScript and HTML 4.01

I've just been testing some code, and I can't get this to work:
<HTML>
<head>
<title> Page 1 </title>
<script>
function myFunction()
{
var x=document.getElementById("myEmail")
document.write(x)
}
</script>
</head>
<body>
<form>
<p> Input your email </p>
<input name="myEmail" type="text">
</form>
<button type="button" onclick="myFunction()">Submit Email</button>
</body>
</HTML>
All I'm trying to is have the user type something into a text, being read by the parser, putting it into a variable, then printing the variable on screen. It would help me a lot with other projects I've got on if I knew this. Can anyone help?
NOTE: I don't want to use HTML5 because it removes some of the tags that I like, so could we use HTML 4.01 or something?
Step 1 is to use HTML 5, indent your code, and use semicolons.
<!DOCTYPE html>
<html>
<head>
<title> Page 1 </title>
<script>
function myFunction() {
var x = document.getElementById("myEmail");
document.write(x);
}
</script>
</head>
<body>
<form>
<p> Input your email </p>
<input name="myEmail" type="text">
</form>
<button type="button" onclick="myFunction()">Submit Email</button>
</body>
</html>
Step 2 is to look at what’s being written, see that it’s null, intuit when document.getElementById would return null, and realize that there is no element with an id of myEmail in your document. It just has a name. Drop the form while you’re at it.
<body>
<p>Input your email </p>
<input id="myEmail" type="text">
<button type="button" onclick="myFunction()">Submit Email</button>
</body>
The next step is to try that again and realize that x is an element, not a string, and you want to get its value.
function myFunction() {
var x = document.getElementById("myEmail");
document.write(x.value);
}
The “good future practice” steps are, in no particular order:
Put your script at the bottom and stop using inline event listeners
Put your script in an external file
Use a <label>
If you’re not going to do something more useful than write the e-mail back, consider also using document.body.appendChild(document.createTextNode(…)), which will not obliterate the rest of the document. The DOM is really great.
Add an id to the input
<input name="myEmail" type="text" id="myEmail">
then write the value
document.write(x.value)
document.getElementById returns the DOM element. Printing the DOM element is not meaningful and its output may vary by browser.
What you want is to print the input value of the input field, so check the value property:
function myFunction()
{
var x=document.getElementById("myEmail").value
document.write(x)
}
Secondly, your HTML code does not have an ID attribute on the element, so the getElementById lookup will fail. Add an ID:
<input name="myEmail" type="text" id="myEmail">
Regarding your note about HTML 4 vs. HTML 5.
NOTE: I don't want to use HTML5 because it removes some of the tags that I like, so could we use HTML 4.01 or something?
That comment is interesting. Without knowing specifically which tags you are referring to, I cannot say why they are removed, but I imagine there is likely an equivalent. HTML 5 does not remove any capabilities of HTML that I am aware of.
That is like saying you won't drive a car with an automatic transmission because it doesn't have a clutch.
All you have to do is add an id attribute having the same value as the value of your name attribute of input type="text" and modify your script to store value instead of the element itself.
<html>
<head>
<title> Page 1 </title>
<script>
function myFunction()
{
var x=document.getElementById("myEmail").value;
document.write(x);
}
</script>
</head>
<body>
<form>
<p> Input your email </p>
<input name="myEmail" id="myEmail" type="text">
</form>
<button type="button" onclick="myFunction()">Submit Email</button>
</body>
</html>

HTML form that links to different pages depending on what user enters?

Is it possible to have an html that links to different websites depending on what text the user enters? In other words, I have a simple text form where users can enter text and then hit submit. As an example of what I'm hoping to do, is there a way to set it up so that if they enter "ABC" and hit submit it takes them to google, but if they enter "XYZ" it takes them to yahoo?
Yes you can, but you need JavaScript, here's a very contrived example almost reminiscent of Web 1.0 scripts. The code sets up a listener on the textfield (keyup), and whenever it changes it calls the function changed, which then evaluates the value in the field. If it matches 'XYZ', it then sets the form's action property to be the URL where you want the form submission. In this particular case, the URL to will be something that doesn't exist. Now of course this is not a complete solution and you'll have to spend a bit of time getting the handler to work correctly.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<form id="myform">
<input type="text" id="mytext" onkeyup="changed()">
</form>
<script type="text/javascript">
function changed()
{
var v = document.getElementById('mytext').value;
if("XYZ" === v)
{
var action = "http://www.foobar.nothing/" + v;
document.getElementById('myform').action = action;
}
}
</script>
</body>
</html>

Javascript redirect on form submit depending on input

I'm working on a simple javascript quiz, and I can't for the life of me get Javascript to submit the form and open the result in the same page, regardless of whether I use location.href, open.window, or whether I set "_self" as the target. Doesn't seem to matter what I do...
function answer() {
var response = document.getElementById('answer').value;
if (response == "correctanswer")
location.href('right.html');
else
location.href('wrong.html');
}
<form onSubmit="answer()" id="answer" target="_self">
<input type="text" maxlength="55" class="box" autofocus />
<input type="submit" class="submit" value="SUBMIT" />
</form>
So, what I want to happen is, when the user submits the form, they go to "right.html" if they typed correctanswer into the text box, or "wrong.html" if they typed anything else.
I've got it running fine, except for the fact that no matter what I do I can't get the resulting page to open in _self, but rather in another window. Every time.
Been driving me crazy all night.
Five things:
Remove the target attribute of form entirely. The default is the same window. Although it doesn't really matter, because:
Cancel the submit event by returning false in your onSubmit, since you're handling the form in your own code. One easy way to do this is have your function return false, and in the onSubmit, return the result of the call.
This line is incorrect:
var response = document.getElementById('answer').value;
form elements don't have a value. You'd want to put the id on the input type="text" element instead.
The href on location is not a function, it's a property. You just assign to it (or just assign directly to location).
This one's a bit subtle: Because you have a global function called answer, and you have an element with an id "answer", there's a conflict: Both want to end up as properties of the window object (one of many reasons not to use old DOM0 onxyz attributes — or global functions, come to that). So you need to change the name of one of them, e.g., change the function to checkAnswer or similar.
So:
<form onSubmit="return checkAnswer();">
<input id="answer" type="text" maxlength="55" class="box" autofocus />
<input type="submit" class="submit" value="SUBMIT" />
</form>
And:
function checkAnswer(){
var response = document.getElementById('answer').value;
if (response == "correctanswer")
location = 'right.html';
else
location = 'wrong.html';
return false;
}
Full Example: Live Copy | Live Source
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<form onSubmit="return checkAnswer();">
<input id="answer" type="text" maxlength="55" class="box" autofocus />
<input type="submit" class="submit" value="SUBMIT" />
</form>
<script>
function checkAnswer(){
var response = document.getElementById('answer').value;
if (response == "correctanswer")
location = 'http://jsbin.com/ukifoh/1'; // 'right.html';
else
location = 'http://jsbin.com/ukifoh/2'; // 'wrong.html';
return false;
}
</script>
</body>
</html>
I would recommend always using consistent, useful code indentation, and I'm a big fan of always using blocks, not just statements, with control structures.

Categories

Resources