Javascript won't output values from input box - javascript

I want to user to press submit button so that their name and age is displayed in the input box with name="output"?
I have 3 input boxes, one asking for name and the other for age while the other one provides output. I am trying to use the function output() to display the last input box.
I am confused about where I am going wrong, do I need a .value?
<!doctype html>
<html>
<head>
<style>
.formdiv{
align: center;
}
</style>
</head>
<body>
<script language="javascript" type="text/javascript">
function output(){
var name = getElementByName('firstName');
var Age= getElementByName('age');
var out = document.write(name+Age);
document.getElementByName('output') = out;
}
</script>
<h1><strong><em><center>Payment Details</center></em></strong> </h1>
<div class="formdiv">
<fieldset><center>
<legend> Enter the following Info:</legend>
<br />
<label> Name </label>
<input type="text" name="firstName" placeholder="John" required="required"></input>
<br/>
<br/>
<label>Age </label>
<input type="number" name="age" maxlength="2" required="required"></input>
</fieldset>
</center>
</div>
<div>
<center>
<button onClick="output()">Submit</button><br/>
<label for="output">Output</label>
<br/>
<input type="textbox" name="output"></input>
</center>
</div>
</body>
</html>

Here's a working version of your code.
There's no method getElementByName (but getElementsByName) - you should use document.getElementById() (Read about it here)
You should use the value of the input element.
<!doctype html>
<html>
<head>
<style>
.formdiv{
align: center;
}
</style>
</head>
<body>
<script language="javascript" type="text/javascript">
function output(){
var name = document.getElementById('firstName').value;
var Age= document.getElementById('age').value;
document.getElementById('output').value = name+Age;
}
</script>
<h1><strong><em><center>Payment Details</center></em></strong> </h1>
<div class="formdiv">
<fieldset><center>
<legend> Enter the following Info:</legend>
<br />
<label> Name </label>
<input type="text" id="firstName" placeholder="John" required="required"></input>
<br/>
<br/>
<label>Age </label>
<input type="number" id="age" maxlength="2" required="required"></input>
</fieldset>
</center>
</div>
<div>
<center>
<button onClick="output()">Submit</button><br/>
<label for="output">Output</label>
<br/>
<input type="textbox" id="output"></input>
</center>
</div>
</body>
</html>

getElementsByName (note: Elements, not Element) returns a list of Elements, in this case your <input>s. So first of all, you need to select the first (in your case your only one) using getElementsByName(...)[0]. Then you get one Element.
However you do not want to output the entire element (which is an Object, not a String, and converted to a string it likely won't be what you expect), so you need to select the value property of that Element. So yes, you need to add .value, just as you assumed:
function output(){
var name = getElementsByName('firstName')[0].value;
var Age= getElementsByName('age')[0].value;
Then, document.write writes the argument to a new document directly, which results in an emtpy page with nothing else on it but that string. This isn't what you want, so you don't need that. ALl you do want is to assign a new variable called out with that string:
var out = name+Age;
Then to assigning the new value to the output field - you don't want to replace the Element by a string (that wouldn't even work), but it's value, so you need the .value again:
document.getElementsByName('output')[0].value = out;
}
That should do the trick.
(In addition to that, you might want to use name + " " + Age instead of simply name+Age, as otherwise you end up with "John Doe23" instead of "John Doe 23" which you likely want)

There are a few things wrong with your code:
there is no such thing as getElementByName - it is getElementById
changing to the above, you need to add ids to your input elements
you need to use the value of the returned object from getElementById
The above will get your code working, but also, the center tag is obsolete and you shouldn't use it
Inputs are self closing tags so you don't need </input>
<!doctype html>
<html>
<head>
<style>
.formdiv {
align: center;
}
</style>
</head>
<body>
<script language="javascript" type="text/javascript">
function output() {
var name = document.getElementById('firstName').value;
var Age = document.getElementById('age').value;
var out = name + Age;
document.getElementById('output').value = out;
}
</script>
<h1><strong><em><center>Payment Details</center></em></strong> </h1>
<div class="formdiv">
<fieldset>
<center>
<legend>Enter the following Info:</legend>
<br />
<label>Name</label>
<input type="text" name="firstName" id="firstName" placeholder="John" required="required"></input>
<br/>
<br/>
<label>Age</label>
<input type="number" name="age" id="age" maxlength="2" required="required"></input>
</fieldset>
</center>
</div>
<div>
<center>
<button onClick="output()">Submit</button>
<br/>
<label for="output">Output</label>
<br/>
<input type="textbox" name="output" id="output"></input>
</center>
</div>
</body>
</html>

Related

Using Javascript To Show Values From HTML

I'm trying to create a HTML Page with multiple forms, and I would like
to show the values from the form on the same page (wiping the original HTML), but after using the button, nothing shows up (the page like reloaded)
Here's the code for HTML :
function Results() {
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var gender = document.getElementById('gender').value;
var date = document.getElementById('birthday').value;
if (document.getElementById('genderM').checked) {
gender = document.getElementById('genderM').value;
} else if (document.getElementById('genderF').checked) {
gender = document.getElementById('genderF').value;
}
document.writeIn("<h3>Thank You! Here's Your Precious Data! </h3>"); document.writeIn("<p> Your Name Is : </p>" + fname + lname); document.writeIn("<p> Gender : " + gender); document.writeIn("<p> Birthday : " + birthday);
document.getElementById('forms').innerHTML = forms;
}
<!DOCTYPE HTML>
<html>
<head>
<title> The Page Number 2 </title>
<link rel="stylesheet" type="text/css" href="page2.css">
</head>
<body>
<h1> Please fill in the form for exciting contents! </h1>
<hr size="5px" color="black">
<div id="forms" class="forms">
<form onsubmit="Results()" method="post">
<div class="textFirst">
First Name
</div>
<input id="fname" type="text" name="fname"> <br>
<br>
<div class="textLast">
Last Name <br>
</div>
<input id="lname" type="text" name="lname"> <br>
<br>
<div class="textGender">
Gender <br>
<input id="genderM" type="radio" name="gender" value="male"> Male <br>
<input id="genderF" type="radio" name="gender" value="female"> Female <br>
</div>
<br>
<div class="textBirth">
Birthday <br>
</div>
<input id="birthday" type="date" name="birthday"> <br>
<input id="submit" class="buttonagain" type="submit" value="Submit!" />
</form>
</div>
</body>
</html>
Any ideas what should I do?
Edit : I'm not able to use php or server for this
Your code is riddled with syntax errors: missing parentheses, missing + operators, etc.
document.writeIn (with an uppercase I) is not a function; document.writeln (with a lowercase L) is.
<script> tags aren't self-closing, i.e. you have to write <script src="scriptPage2.js"></script>
document.getElementById('gender') returns null, because there is no element with id="gender".
You're trying to write birthday but you never declared that variable.
I have no idea what you're trying to accomplish with document.getElementById('forms').innerHTML = forms;
In general, you should make use of the browser's built-in debugger to catch all these errors. If you're using Chrome or Firefox, press Ctrl+Shift+I (in IE or Edge, press F12) and open the "Console" tab; you will see all the errors there as the JS parser encounters them.
Once that's all fixed, remove the submit event handler from <form>, and change your submit button like this:
<input id="submit" class="buttonagain" type="button" onclick="Results()" value="Submit!" />
Note the change of type from submit to button. This will prevent the page from reloading, which is the expected behavior when submitting a form.
You don't need the return and ; when calling a js function in html
<form onsubmit="Results()" method="post">
This is your answer.
function Results() {
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var gender;
var date = document.getElementById('birthday').value;
if (document.getElementById('genderM').checked) {
gender = "Male";
} else {
gender = "Female"
}
document.writeln("<h3>Thank You! Here's Your Precious Data! </h3>");
document.writeln("<p> Your Name Is : </p>" + fname + " " + lname);
document.writeln("<p> Gender : " + gender);
document.writeln("<p> Birthday : " + date);
document.getElementById('forms').style.display = "none";
}
<!DOCTYPE HTML>
<html>
<head>
<title> The Page Number 2 </title>
<link rel="stylesheet" type="text/css" href="page2.css">
</head>
<body>
<h1> Please fill in the form for exciting contents! </h1>
<hr size="5px" color="black">
<div id="forms" class="forms">
<form onsubmit="Results();" method="post">
<div class="textFirst">
First Name
</div>
<input id="fname" type="text" name="fname" required> <br>
<br>
<div class="textLast">
Last Name <br>
</div>
<input id="lname" type="text" name="lname"required> <br>
<br>
<div class="textGender">
Gender <br>
<input id="genderM" type="radio" name="gender" value="male" required> Male <br>
<input id="genderF" type="radio" name="gender" value="female"> Female <br>
</div>
<br>
<div class="textBirth">
Birthday <br>
</div>
<input id="birthday" type="date" name="birthday"required> <br>
</div>
<input id="submit" class="buttonagain" type="submit" value="Submit!" />
</div>
</form>
</body>
</html>

To show error message without alert box in Java Script

Please correct the below code it is not working as expected i.e, i need a error message to be shown just beside the textfield in the form when user enters an invalid name
<html>
<head>
<script type="text/javascript">
function validate() {
if(myform.fname.value.length==0)
{
document.getElementById("fname").innerHTML="this is invalid name ";
}
}
</script>
</head>
<body>
<form name="myform">
First_Name
<input type=text id=fname name=fname onblur="validate()"> </input>
<br> <br>
Last_Name
<input type=text id=lname name=lname onblur="validate()"> </input>
<br>
<input type=button value=check>
</form>
</body>
</html>
Try this code
<html>
<head>
<script type="text/javascript">
function validate() {
if(myform.fname.value.length==0)
{
document.getElementById('errfn').innerHTML="this is invalid name";
}
}
</script>
</head>
<body>
<form name="myform">
First_Name
<input type=text id=fname name=fname onblur="validate()"> </input><div id="errfn"> </div>
<br> <br>
Last_Name
<input type=text id=lname name=lname onblur="validate()"> </input>
<br>
<input type=button value=check>
</form>
</body>
</html>
I m agree with #ReNjITh.R answer but If you want to display error message just beside textbox. Just like below
<html>
<head>
<script type="text/javascript">
function validate()
{
if(myform.fname.value.length==0)
{
document.getElementById('errfn').innerHTML="this is invalid name";
}
}
</script>
</head>
<body>
<form name="myform">
First_Name
<input type=text id=fname name=fname onblur="validate()" /><span id="errfn"></span>
<br> <br>
Last_Name
<input type=text id=lname name=lname onblur="validate()"/><br>
<input type=button value=check />
</form>
</body>
web masters or web programmers, please insert
<!DOCTYPE html>
at the start of your page. Second you should enclose your attributes with quotes like
type="text" id="fname"
input element should not contain end element, just close it like:
/>
input element dont have innerHTML, it has value sor your javascript line should be:
document.getElementById("fname").value = "this is invalid name";
Please write in organized way and make sure it is convenient to standards.
you can try it like this
<html>
<head>
<script type="text/javascript">
function validate()
{
var fnameval=document.getElementById("fname").value;
var fnamelen=Number(fnameval.length);
if(fnamelen==0)
{
document.getElementById("fname_msg").innerHTML="this is invalid name ";
}
}
</script>
</head>
<body>
<form name="myform">
First_Name
<input type=text id=fname name=fname onblur="validate()"> </input>
<span id=fname_msg></span>
<br> <br>
Last_Name
<input type=text id=lname name=lname onblur="validate()"> </input>
<br>
<input type=button value=check>
</form>
</body>
</html>
You can also try this
<tr>
<th>Name :</th>
<td><input type="text" name="name" id="name" placeholder="Enter Your Name"><div id="name_error"></div></td>
</tr>
function register_validate()
{
var name = document.getElementById('name').value;
submit = true;
if(name == '')
{
document.getElementById('name_error').innerHTML = "Name Is Required";
return false;
}
return submit;
}
document.getElementById('name').onkeyup = removewarning;
function removewarning()
{
document.getElementById(this.id +'_error').innerHTML = "";
}
First you are trying to write to the innerHTML of the input field. This will not work. You need to have a div or span to write to. Try something like:
First_Name
<input type=text id=fname name=fname onblur="validate()"> </input>
<div id="fname_error"></div>
Then change your validate function to read
if(myform.fname.value.length==0)
{
document.getElementById("fname_error").innerHTML="this is invalid name ";
}
Second, I'm always hesitant about using onBlur for this kind of thing. It is possible to submit a form without exiting the field (e.g. return key) in which case your validation code will not be executed. I prefer to run the validation from the button that submits the form and then call the submit() from within the function only if the document has passed validation.
Try like this:
function validate(el, status){
var targetVal = document.getElementById(el).value;
var statusEl = document.getElementById(status);
if(targetVal.length > 0){
statusEl.innerHTML = '';
}
else{
statusEL.innerHTML = "Invalid Name";
}
}
Now HTML:
<!doctype html>
<html lang='en'>
<head>
<title>Derp...</title>
</head>
<body>
<form name="myform">
First_Name
<input type="text" id="fname" name="fname" onblur="validate('fname','fnameStatus')">
<br />
<span id="fnameStatus"></span>
<br />
Last_Name
<input type="text" id="lname" name="lname" onblur="validate('lname','lnameStatus')">
<br />
<span id="lnameStatus"></span>
<br />
<input type=button value=check>
</form>
</body>
</html>
You should use .value and not .innerHTML as it is a input type form element
<html>
<head>
<script type="text/javascript">
function validate() {
if(myform.fname.value.length==0)
{
document.getElementById("fname").value="this is invalid name ";
}
}
</script>
</head>
<body>
<form name="myform">
First_Name
<input type=text id=fname name=fname onblur="validate()"> </input>
<br> <br>
Last_Name
<input type=text id=lname name=lname onblur="validate()"> </input>
<br>
<input type=button value=check>
</form>
</body>
</html>
Setting innerHtml of input value wont do anything good here, try with other element like span, or just display previously made and hidden error message.
You can set value of name field tho.
<head>
<script type="text/javascript">
function validate() {
if (myform.fname.value.length == 0) {
document.getElementById("fname").value = "this is invalid name ";
document.getElementById("errorMessage").style.display = "block";
}
}
</script>
</head>
<body>
<form name="myform">First_Name
<input type="text" id="fname" name="fname" onblur="validate()"></input> <span id="errorMessage" style="display:none;">name field must not be empty</span>
<br>
<br>Last_Name
<input type="text" id="lname" name="lname" onblur="validate()"></input>
<br>
<input type="button" value="check" />
</form>
</body>
FIDDLE
try this
<html>
<head>
<script type="text/javascript">
function validate() {
if(myform.fname.value.length==0)
{
document.getElementById("error").innerHTML="this is invalid name ";
document.myform.fname.value="";
document.myform.fname.focus();
}
}
</script>
</head>
<body>
<form name="myform">
First_Name
<input type="text" id="fname" name="fname" onblur="validate()"> </input>
<span style="color:red;" id="error" > </span>
<br> <br>
Last_Name
<input type="text" id="lname" name="lname" onblur="validate()"> </input>
<br>
<input type=button value=check>
</form>
</body>
</html>
You should place your script code after your HTML code and within your body tags. That way it doesn't run before the html code.

getElementById(element).innerHTML cache?

This is my page code:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Marketing Tracking</title>
</head>
<body>
<form action="#" id="form" method="post">
<div id="namevalues">
<span id="span:1">
<input type="text" id="name:1" onchange="changed(this)" style="width:300px;"/>
<input id="value:1" type="number" min="0" value="0" /><br /></span>
</div>
<input type="button" id="add" value="Add 1" />
<br />
<textarea name="talk" style="width:500px;height:175px;"></textarea>
<br />
<input type="button" id="update" value="Update"/>
</form>
<script>
function get(a){return document.getElementById(a);}
up=get("update");
up.onclick = function(){
get("form").submit();
}
get("name:1").onchange = function(){changed(this)};
get("add").onclick = function(){add()};<% z=2 %>
function changed(ele){
id=ele.id;
val=ele.value;
id=id.split(":")[1];
get("value:"+id).name=get("name:"+id).value;
}
function add(){
document.getElementById("namevalues").innerHTML+='<span id="span:'+z+'"><input type="text" id="name:'+z+'" onchange="changed(this)" style="width:300px;"/><input id="value:'+z+'" type="number" min="0" value="0" /><br /></span>';
}
</script>
</body>
</html>
I am very confused as to why when I press the Add 1 button enter some text and then press the Add 1 button again the text that I just entered disappears!
If anyone could give some insight to this it would be greatly appreciated.
The reason your other values disappear is because when you do something.innerHTML += something it will rewrite the HTML for that zone (meaning what was there before is gone and will be replaced with fresh new HTML). What you probably want to do is something along this :
function add(){
var div = document.createElement("div");
div.innerHTML = '<span id="span [... the rest of the code ...]<br /></span>';
document.getElementById("namevalues").appendChild(div);
}
Using appendChild won't alter the other element that are already in the div namevalues.
Just a small thing but try using
<script type="text/javascript">
When I was using inner.document stuff I had all kinds of problems until I added that code.

Submit Button Not Calling Function

Please forgive any potential lapses in protocol and/or formatting. I'm new at this. Clicking on my "submit" button does not call the function cost(). What am I doing wrong?
<html>
<head>
<script type="text/javascript">
function cost() {
mpg = document.getElementById("mpg");
distance = document.getElementById("distance");
gasPrice = document.getElementById("gasPrice");
alert("<p>" + Math.round((distance / mpg) * gasPrice) + "</p>");
}
</script>
<h1>Trip Cost Calculator</h1>
</head>
<p> Enter mpg (miles): </p>
<input type="text" id="mpg">
</input>
</body>
<body>
<p> Enter distance (miles): </p>
<input type="text" id="distance">
</input>
</body>
<body>
<p> Enter gas price (dollars): </p>
<input type="text" id="gasPrice">
</input>
</body>
<body>
</br>
<input type="button" id="submit" value="Submit" onclick="cost()"/>
</body>
You are manipulating objects.Retrieve values using value property like this.
mpg = document.getElementById("mpg").value;
distance = document.getElementById("distance").value;
gasPrice = document.getElementById("gasPrice").value;
You need value of those elements, not the element it self:
<script type="text/javascript">
function cost() {
mpg = document.getElementById("mpg").value;
distance = document.getElementById("distance").value;
gasPrice = document.getElementById("gasPrice").value;
alert(Math.round((distance / mpg) * gasPrice));
}
</script>
And you also need to remove all those extra <body> tags.
Your body tags are incorrect. You also need to close your html tag. Moreover, use the .value property to access the input fields.
<html>
<head>
<script type="text/javascript">
function cost() {
mpg = document.getElementById("mpg").value;
distance = document.getElementById("distance").value;
gasPrice = document.getElementById("gasPrice").value;
alert("<p>" + Math.round((distance / mpg) * gasPrice) + "</p>");
}
</script>
<h1>Trip Cost Calculator</h1>
</head>
<body>
<p> Enter mpg (miles): </p>
<input type="text" id="mpg">
</input>
<p> Enter distance (miles): </p>
<input type="text" id="distance">
</input>
<p> Enter gas price (dollars): </p>
<input type="text" id="gasPrice">
</input>
</br>
<input type="button" id="submit" value="Submit" onclick="cost()"/>
</body>
</html>
Things go wrong on all kinds of levels here, first and for all make sure you have valid html. When working with DOM nodes it's always best to make sure your browser can create a valid dom tree and that works best with valid html. Check http://validator.w3.org
Second, in your cost() function you aren't fetching the values of the input fields but the fields themself. Ofcourse this results in some weird behaviour which might explain you thinking the cost() function isn't executed. It probably is but is throwing errors you don't notice (check the debug/error console of your browser)
I've fixed up your example, check it, learn from it and read up on webstandards :)
http://jsfiddle.net/vyfqC/3/
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function cost() {
mpg = document.getElementById("mpg").value;
distance = document.getElementById("distance").value;
gasPrice = document.getElementById("gasPrice").value;
alert("<p>" + Math.round((distance / mpg) * gasPrice) + "</p>");
}
</script>
<title>Trip cost calculator</title>
</head>
<body>
<h1>Trip Cost Calculator</h1>
<p> Enter mpg (miles): </p>
<input type="text" id="mpg" />
<p> Enter distance (miles): </p>
<input type="text" id="distance" />
<p> Enter gas price (dollars): </p>
<input type="text" id="gasPrice" />
<input type="button" id="submit" value="Submit" onclick="cost()"/>
</body>
​

Copying data from one text box to another using Java Script

I want to copy data from one text box to another in html automatically ie., as I edit the first text box the second one should reflect the same spontaneously
call javascript function on onkeypresss
function copy_data(val){
var a = document.getElementById(val.id).value
document.getElementById("copy_to").value=a
}
EDITED USE onkeyup or onblur instead
<html>
<head>
<script>
function copy_data(val){
var a = document.getElementById(val.id).value
document.getElementById("copy_to").value=a
}
</script>
</head>
<body>
<input type="text" name ="a" id="copy_from" onkeyup="copy_data(this)"/>
<input type="text" name ="a" id="copy_to"/>
</body>
</html>
In jQuery, something like this:
$("#txtBox1").keypress(function() {
$("#txtBox2").val($(this).val());
}
You do easily with JQuery:
<input type="text" id="box1" />
<input type="text" id="box2" />
<script type="text/javascript">
$(function(){
$("#box1").keypress(function()
{
$("#box2").val($(this).val());
}
});
</script>
You can achieve by this...
function FillBilling(f) {
if(f.billingtoo.checked == true) {
f.billingname.value = f.shippingname.value;
f.billingcity.value = f.shippingcity.value;
}
}
To add more fields, just add to the parameters shown above...like this:
f.billingstate.value = f.shippingstate.value;
f.billingzip.value = f.shippingzip.value;
The HTML for the form you will use looks like this:
<b>Mailing Address</b>
<br><br>
<form>
Name:
<input type="text" name="shippingname">
<br>
City:
<input type="text" name="shippingcity">
<br>
<input type="checkbox" name="billingtoo" onclick="FillBilling(this.form)">
<em>Check this box if Billing Address and Mailing Address are the same.</em>
<P>
<b>Billing Address</b>
<br><br>
Name:
<input type="text" name="billingname">
<br>
City:
<input type="text" name="billingcity">
</form>

Categories

Resources