Posting JS variable from HTML form - javascript

Im a bit of a newbie.
Im trying to post some data I have in a JavaScript variable to my server.
Iv looked around and from what I gather I need to put it in as part of a form? is there anyway to hide this form box?
Do I place this information in the value section of the form?
Eg.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Namespace</title>
<script type="text/javascript" charset="utf-8">
functionAddPostData(){
var name = "Christopher";
var last = "Bar";
var formInfo = document.forms['info'];
name = formInfo.elements["first"].innerHTML;
last = formInfo.elements["surname"].innerHTML;
}</script>
</head>
<body>
<form action="script.php" method="post" allign="bottom">
<label for="info">
<input type="text" name="first" value="" size ="40" />
<input type="text" name="surname" value="" size ="60" />
<input type= "submit" name="submitted" value="info" allign="middle"/>
</form>
</body>
</html>
This is my best guess? Am I heading in the right direction? Is there a way to hide the form boxes?

Use hidden fields to post the data to server if you dont want to show the textbox in the UI.
<input type="hidden" name="first" value="" size ="40" />
You should set the onSubmit of form to functionAddPostData which will get called when you submit the form. Also the form should have a name atttibute since you are trying to access it by name.
The form element values should be set as below
var formInfo = document.forms['info'];
formInfo.first.value = name;
formInfo.surname.value = last;

There are a couple things wrong with the code you posted, which is why its not working. It's late so instead of a line by line analysis I will post a modified version that you can look over. I would recommend reading through an HTML guiide like W3 Schools and to also go through a good javascript tutorial (like Webmonkey. Cheers.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Namespace</title>
<script type="text/javascript" charset="utf-8">
function AddPostData(){
var name = "Christopher";
var last = "Bar";
var formInfo = document.forms['info'];
name = formInfo.elements["first"].value;
last = formInfo.elements["surname"].value;
alert(name + ' ' + last);
}</script>
</head>
<body>
<form id="info" action="script.php" method="post" align="bottom">
<p>For</p>
<input type="text" name="first" value="" size ="40" />
<input type="text" name="surname" value="" size ="60" />
<input type= "submit" name="submitted" value="info" align="middle" onclick="AddPostData();"/>
</form>
</body>
</html>

Related

Form with input and output immediately reload the page after printing the output

I need to do a simple homework where you enter two integers in two text fields of a form and then you compute the sum and you print it in a "text field (not editable)". My program seems to work but it prints the right output and immediately reload the page. I want the page to remain with the printed output if the user does not click again on "submit" button
Here is my code HTML & JS :
function updateExpr() {
var x1 = document.getElementById("n1").value;
var x2 = document.getElementById("n2").value;
var sum = +x1 + +x2;
document.getElementById("sum").innerHTML = +x1 + +x2;
}
<!DOCTYPE html>
<html>
<head>
<title>Number in a form</title>
<link href="mystyle.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="function.js">
</script>
</head>
<body>
<div id="mainDiv">
<H3>Insert two positive numbers</H3>
<form>
First number:<br>
<input id="n1" type="text" name="firstname"><br>
Second number:<br>
<input id="n2" type="text" name="lastname">
<BR>
<input type="submit" value="Submit" onClick="updateExpr()"/><BR><BR>
</form>
The sum is:<br>
<output id="sum" name="x" for="a b"></output>
</div>
<noscript>
Sorry: Your browser does not support or has disabled javascript
</noscript>
</body>
</html>
When form is submited, the page will be reloaded. To prevent this you should change input type attribute from submit to button.
<input type="submit" value="Submit" onClick="updateExpr()"/>
to
<input type="button" value="Submit" onClick="updateExpr()"/>
You can simply avoid server call by changing your form tag
<form onSubmit="return false">
You dont really need a form to do something like this.
Forms send values to the backend, e.g. a server.
You only want to manipulate some front-end elements like a container to have some new text inside it.
a <form> tag typically sends you to some URI with some aprameters,
this is done by the actions attribute.
<form action="addnames.php">
for example would call the addnames.php script on your server...
You dont need a server tho..look below:
function updateExpr() {
var x1 = document.getElementById("n1").value;
var x2 = document.getElementById("n2").value;
var sum =x1 +x2;
document.getElementById("sum").innerHTML = sum;
}
<h2>HTML Forms</h2>
First name:<br>
<input id="n1" type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input id="n2" type="text" name="lastname" value="Mouse">
<br><br>
<button type="submit" onclick="updateExpr()">Submit</button>
<div id="sum">
</div>
<script>
</script>
I would recommand you to add onSubmit method to the form instead of onclick to the input.
Also you better add a return : false to your function and add onsubmit="return updateExpr()".
function updateExpr() {
var x1 = document.getElementById("n1").value;
var x2 = document.getElementById("n2").value;
var sum = +x1 + +x2;
document.getElementById("sum").innerHTML = +x1 + +x2;
return false;
}
<!DOCTYPE html>
<html>
<head>
<title>Number in a form</title>
<link href="mystyle.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="function.js">
</script>
</head>
<body>
<div id="mainDiv">
<H3>Insert two positive numbers</H3>
<form onsubmit="return updateExpr()">
First number:<br>
<input id="n1" type="text" name="firstname"><br>
Second number:<br>
<input id="n2" type="text" name="lastname">
<BR>
<input type="submit" value="Submit" onClick="updateExpr()"/><BR><BR>
</form>
The sum is:<br>
<output id="sum" name="x" for="a b"></output>
</div>
<noscript>
Sorry: Your browser does not support or has disabled javascript
</noscript>
</body>
Another way of doing this would have been to add a button outside of the form linked to the function by onclick event
juste add preventDefault(), like this
function updateExpr(e) {
e.preventDefault();
var x1 = document.getElementById("n1").value;
var x2 = document.getElementById("n2").value;
var sum = +x1 + +x2;
document.getElementById("sum").innerHTML = +x1 + +x2;
}

Create a "calculation form" in javascript

so I have a project now, as an addition to my company's website, we want to show our clients how much they can save on gas by buying one of our electric cars, I'm responsible for making it happen, I don't know how to approach this using javascript, can you guys give me a hand? our marketing guy got the idea from this website, that is basically what we want, but I was hoping i could make it a little better on some aspects:
1st-the client wouldn't have to press submit to see the results, as they fill the last field, the calculated part is populated automatically, for this i've been fiddling with the onChange event, unsuccessfully though xD
here's what I have so far, it is not working, at least on dreamweaver's live mode, haven't tested it online yet as I was hoping to develop the whole thing offline:
<script type="text/javascript">
function calc(){
var km=document.getElementById(km).value;
var euro=document.getElementById(euro).value;
var consumo=document.getElementById(consumo).value;
var cem_km=consumo*euro;
var fossil_day=(cem_km*km)/100;
return fossil_day;
}
</script>
<form name="calc" id="calc" >
<p>
Km/dia
<input type="text" name="km" id="km" value="" />
</p>
<p>
€/Litro
<input type="text" name="euro" id="euro" value="" />
</p>
<p>
Litros/100km
<input type="text" onChange="calc()" name="consumo" id="consumo" value="" />
</p>
<input type="button" onClick="calc()" name="submit" id="submit" value="Calcular" />
<script type="text/javascript">
var fossil_day = calc();
document.write('<p>'+fossil_day+'</p>');
</script>
</form>
Please note that although I have this already, I wouldnt mind not doing this at all and using another solution, even if it doesnt use forms, I'm just showing what i have already so you can tell me how I'm wrong and how I can have a better approach at it
there are many errors inside your code
document.getElementById() needs the element id in brackets ''
you can't create a element with the same name,id as a function calc else it will throw an error as it's an object and not a function.
your executing the function onload... but you want it to be executed when the button is clicked & onchange.
you don't need to add value if empty and name if you use getElementById
return false in the function on buttons inside form else it could send the form and so refresh the page.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>calc</title>
<script>
function calc(){
var km=document.getElementById('km').value;
var euro=document.getElementById('euro').value;
var consumo=document.getElementById('consumo').value;
var cem_km=consumo*euro;
var fossil_day=(cem_km*km)/100;
document.getElementById('result').innerHTML=fossil_day;
return false
}
</script>
</head>
<body>
<form>
<p>Km/dia<input type="text" id="km"/></p>
<p>€/Litro<input type="text" id="euro" /></p>
<p>Litros/100km<input type="text" onChange="calc()" id="consumo" /></p>
<input type="button" onClick="calc()" value="Calcular" />
</form>
<div id="result"></div>
</body>
</html>
Useing jQuery (and html5 type="number" form fields):
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form>
<p>
Km/dia
<input type="number" name="km" id="km" value="" />
</p>
<p>
€/Litro
<input type="number" name="euro" id="euro" value="" />
</p>
<p>
Litros/100km
<input type="number" name="consumo" id="consumo" value="" />
</p>
<div id="fossil-day"></div>
</form>
<script src="http://codeorigin.jquery.com/jquery-1.10.2.min.js"></script>
<script>
function calculate(){
var km = $('#km').val();
var euro = $('#euro').val();
var consumo = $('#consumo').val();
var cem_km = consumo*euro;
var fossil_day = (cem_km*km)/100;
$('#fossil-day').html(fossil_day);
}
$(function() {
/*when #consumo input loses focus, as per original question*/
$('#consumo').blur(function(){
calculate();
});
});
</script>
</body>
</html>

Alert box shows form data when clicking button

I am looking to create a button at the bottom of a form that will create an alert box that will show the form data entered. Form includes:
First Name
Last Name
Address 1
Address 2
City
State
Zip
Phone
Fax
Once the form is completed, the button is clicked and an alert box pops up showing the form data entered.
Does anyone know how to accomplish without the form actually being submitted or validated? There is no database for the form data to be submitted to, so there is no database to pull the information from.
Any help would be greatly appreciated.
I have not included the form code due to its length, but the current code I am working with for the Alert Box looks like this:
<script>
function display_alert()
{
alert("");
}
</script>
<body>
<input type="button" onclick="display_alert()" value="Display alert box">
</body>
If I get it right you need something like this:
<html>
<head>
<script type="text/javascript">
window.onload = function(){
document.getElementById('send').onclick = function(e){
alert(document.getElementById("name").value);
return false;
}
}
</script>
</head>
<body>
<form method="post">
<input type="text" name="name" id="name" />
<input type="submit" name="send" id="send" value="send" />
</form>
</body>
</html>
I don't really get what you mean with a database to pull the information from, but the example uses a click event to get the data from the form field and shows it in an alert without a submit.
html code:
<html>
<SCRIPT SRC="PR8_4.JS"></SCRIPT>
<body>
<form name=details>
<table>
<tr><td>ENTER FRIST NAME:<input type=text name=fname></td></tr>
<tr><td>ENTER LAST NAME:<input type=text name=lname></td></tr>
<tr><td>ENTER PHONE NUM :<input type=text name=phnum></td></tr>
</table>
<input type="button" value="Click Me" onclick="display();">
</form>
</body>
</html>
javascript code:
function display()
{
var x=document.details.fname.value;
var y=document.details.lname.value;
var z=document.details.phnum.value;
alert("FIRST NAME:"+x+" "+"LAST NAME:"+y+" "+"PHONE NUMBER:"+z);
}
To stop a form submitting you can create an onsubmit event within the tag and return false - e.g. ...form elements.... This has the benefit of working when someone submits the form by pressing the enter key as well as pressing the submit button.
Thus, to achieve what you desire you could create a function (lets call it formAlert) and call it from the onsubmit event e.g. ...form elements...
The formAlert function would look something like:
function formAlert() {
alert_string = '';
alert_string = alert_string + document.getElementById('first_name').value;
alert_string = alert_string + ' ';
alert_string = alert_string + document.getElementById('last_name').value;
alert(alert_string);
}
and this would correspond to a form looking like:
<form id="foo" onsubmit="formAlert(); return false;">
<p><label for="first_name">First Name<label><input type="text" id="first_name" value="fred" /></p>
<p><label for="last_name">Last Name<label><input type="text" id="last_name" value="blogs" /></p>
<p><input type="submit" value="click me" /></p>
</form>
Note1, this won't be a pretty modal box - it'll simply display "fred blogs" in a Javascript alert box.
Note2, if there is a Javascript error your form will still submit (although in the example here it'll submit to itself).
Here is a JS Fiddle demonstrating the above code: http://jsfiddle.net/D59su/
I think this might be what you're looking for:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="javascriptform.css">
</head>
<body>
<form name= "details"><div class="box1"><div id="a"><input type="text" name="lastname" placeholder="LAST NAME"></div><br>
<div id="b"><input type="text" name="firstname" placeholder="FIRST NAME"></div><br>
<div id="c"><input type="e-mail" name="email" placeholder="E-MAIL"></div><br>
<div id="d"><input type="password" name="password" placeholder="PASSWORD"></div><br>
<div id="sub-button"><button onclick="getdetails();">submit</button></div></form>
</div>
<script>
function getdetails()
{
var a = document.forms["details"]["lastname"].value;
var b = document.forms["details"]["firstname"].value;
var c= document.forms["details"]["email"].value;
alert("Your name is "+a+" "+b+". Your e-mail is "+c);
}
</script>
</body>
</html>
It Is Very Simple
Using .value will help.
HTML:
<form onsubmit="return myFunction()>
<input type="text" id="name>
<input type="submit" value="SEND">
Use return before your function
Javascript:
function myFunction () {var name = document.getElementById("name").value; alert("Hi " + name)}
After Submitting It Will Show As (If I Write Alex and Submit It)
Hi Alex
Hope it will work

How can I add a row to a table in Javascript without it immediately resetting?

I am trying to learn JavaScript, but I'm struggling with a very simple example.
I have a form and I want to add its contents to a new table row in "catalog" every time the user hits submit.
But when I hit submit using the code below, I see the new table row flash briefly and then disappear, as if the page is being reset.
When I use the commented out code instead (just appending the form contents to body.innerHTML), it works fine.
What am I doing wrong?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4 /loose.dtd">
<html>
<head>
<title>Javascript test</title>
</head>
<script type="text/javascript">
function addItem() {
var itemName = document.getElementById('item_name').value;
var itemPrice = document.getElementById('item_price').value;
var newRow = document.createElement('tr');
//var body = document.getElementById('body');
//body.innerHTML += itemName;
newRow.innerHTML = "<td>" + itemName + "</td><td>" + itemPrice + "</td>";
var catalog = document.getElementById('catalog');
catalog.appendChild(newRow);
}
</script>
<body id="body">
<form><h2>Add an Item to the Catalog</h2>
<p>Item Name: <input type="text" id="item_name" value="" /> Price: <input type="text" id="item_price" value="" /></p>
<input type="submit" onClick="addItem()" value="Add" id="submit" />
<input type="reset" id="reset" />
</form>
<table id="catalog"></table>
</body>
</html>
The input type of 'submit' will submit the form after executing your JavaScript.
If you change the input type to 'button' you will see your code working.
<input type="button" onClick="addItem()" value="Add" id="submit" />
This is also known as a 'PostBack' which involves taking the data in input fields on a form, and posting it to the page again. The data that is posted to the page can be picked up from server-side code as a basis for some further action.
Otherwise, your code is fine. My only suggestion would be to construct tds in the same way as you are constructing the trs
Change type="submit" to type="button"

Image is not getting displaced in the browser

I was doing an exercise on positioning the image, from a book. It says, using DOM, i.e. position, top and left value of the image we can move the image along the browser window using JavaScript.
The thing is i have the image getting displayed but when i enter the coordinates it doesn't get displaced to its new value. Please if someone could tell me where i am going wrong ??
here is the HTML file
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Sample</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="newjavascript.js">
</script>
</head>
<body>
<form action="">
<p>
Xcordinate : <input type="text" id="xCod" /><br/>
Ycordinate : <input type="text" id="yCOd" /><br/>
</p>
<br/>
<input type="submit" value="Set the Coordinates" onclick = "moveIt('image', document.getElementById('xCod').value,
document.getElementById('yCod').value )" />
</form>
<div id="image" style="position: absolute; left:0; top:200px" >
<img src="testing.jpg" alt="Picture Cannot be displayed" />
</div>
</body>
</html>
and the JavaScript file
function moveIt (movee, newTop, newLeft){
dom = document.getElementById(movee).style;
dom.top=newTop+"px";
dom.left=newLeft+"px";
}
I have default browser for Google Chrome
Because it's a type="submit" button, it is posting back and you're seeing the same page over again, you need to return false; to prevent the submit, like this:
<input type="submit" value="Set the Coordinates" onclick = "moveIt('image', document.getElementById('xCod').value,
document.getElementById('yCod').value); return false;" />
Also noticed in setting up the demo that your element IDs are off, this:
Ycordinate : <input type="text" id="yCOd" /><br/>
Should be:
Ycordinate : <input type="text" id="yCod" /><br/>
You can test it out (with both of the above fixes) here.
You have a capitalization issue (or a typo in your post). You have an element in your page with an id of yCOd, but your code is looking for an ID of yCod

Categories