Javascript functions that adds three inputs - javascript

I am new to Javascript so sorry in advance if its because of dumb errors.
I need to add "salaire", "pension" and "autre" and show it in an input after I click a button. I am not sure if I used the right tags in my code probably more suitable ones.
<!DOCTYPE html>
<html>
<head>
<meta charset="urf-8"/>
<script>
function revenue_mensuel()
{
var salaire = document.getelementsbyname("salaire");
var pension = document.getelementsbyname("pension");
var autre = document.getelementsbyname("autre");
return {salaire+pension+autre}
document.getElementById("revenue").value = revenue_mensuel();
}
</script>
<style>
</style>
</head>
<body>
<h1 vos revenus mensuels </h1>
<br/>
<div>
<form>
salaire mensuel (avant impots):
<input type="number and decimal/floats" name="salaire">
</form>
<br/>
<form>
pension alimentaire recus:
<input type="number and decimal/floats" name="pension">
</form>
<br/>
<form>
autre revenue mensuels:
<input type="number and decimal/floats" name="autre">
</form>
<br/>
<form>
total des revenue mensuel:
<input id="revenue" type="text"/>
<input type="button" onclick='revenue_mensuel()'/>
</form>
</body>
</html>

A list of technical issues
Javascript is case-sensitive so method you want is getElementsByName and not getelementsbyname
the getElementsByName return a list of elements (so you need to specify which in the list) in your case it is the 1st one always. so you need to access it with [0]
then you need to extract the actual value of the input with .value.
you need to convert the string to a number. (adding + at the start, or using parseInt will do the trick)
In the concept
You are calling the revenue_mensuel from inside it self, causing an infinite loop.
you do not need to return anything from the function since you assign the result to the element directly.
Html issues
you have left the h1 open
you do not need a different form for each input element
All changes together give
function revenue_mensuel() {
var salaire = +document.getElementsByName("salaire")[0].value;
var pension = +document.getElementsByName("pension")[0].value;
var autre = +document.getElementsByName("autre")[0].value;
document.getElementById("revenue").value = salaire + pension + autre;
}
<h1> vos revenus mensuels </h1>
<br/>
<div>
<form>
salaire mensuel (avant impots):
<input type="number and decimal/floats" name="salaire">
<br/>pension alimentaire recus:
<input type="number and decimal/floats" name="pension">
<br/>autre revenue mensuels:
<input type="number and decimal/floats" name="autre">
<br/>total des revenue mensuel:
<input id="revenue" type="text" />
<input type="button" onclick='revenue_mensuel()' />
</form>
</div>

You should use
<input type="number" name="...">
there is no such thing as type="number and decimal/floats"
This validator will help you fix your code: http://validator.w3.org/

Related

Using For Loop in Javascript?

Also my I need help with the loop to add more names when I put the number 2 instead of 1. Having issues with my code any help is appreciated. I know its simple For Loop coding, but I am stumped.
HTML
<p>Enter First Name: <input type="text" id="firstname">
<span id="firstname_error"></span>
</p>
<p>Enter Last Name: <input type="text" id="lastname">
<span id="lastname_error"></span>
</p>
<p>How Many Pets do you have? (0-3):
<input type="text" id="numpets" size="1" maxlength="1">
<span id="numpets_error"></span>
</p>
<p>List your Pet's names:
<input type="text" id="pet1">
<input type="text" id="pet2">
<input type="text" id="pet3">
</p>
<p><input id="mybutton" type="button" value="Submit Information"></p>
<p id="message"></p>
JavaScript
for(counter=1; counter<=numpets; counter++) {
var PetId = "pet" + counter;
var myPetName = document.getElementById(PetId).value;
// Code to append test into a message variable
}
I have a total of three fields in the var "numpets", if I put the number 1 in that field, it will only the read the name in the number 1 field. If I put 2 it will only read the name in the number 2 field. I need it to be able to read all 3 three fields.
The for loop is ok. You have just to put your loop inside a function and call it with your button. And define the numpets like you did with the var namepet.

Javascript won't output values from input box

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>

How Embed a HTML form with additional element on condition using JavaScript

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>form</title>
<link href="MyStyle.css" rel="stylesheet" type="text/css">
</head>
<body class="form">
<h1>Application Form</h1>
<form class="fdmain" method="post" id="form2" name="form2" action=>
<p>
<label for="textfield">Name:</label>
<input type="text" name="stdname" id="tfname">
</p>
<p>Father Name:
<input type="text" name="fname" id="tffathername">
</p>
<p>
<label for="email">Email:</label>
<input type="email" name="email" id="email">
</p>
<p>
<label for="tel">Tel:</label>
<input type="tel" name="tel" id="tel">
</p>
<p>Select Application Type:
<select name="appselect" id="appselect" onchange="myfunc()">
<option value="" selected>Select Here </option>
<option value="Course_Application">Course Application</option>
<option value="Acc_State">Statement of Account</option>
<option value="Invite">Invitation</option>
<option value="Complain_Application">Complain</option>
<option value="SA_Applications">Student Affair Application</option>
</select>
</p>
<script type="application/javascript">
function myfunc(){
var Appread = document.forms[0].appselect.value;
if(Appread.localeCompare("Course_Application")==0)
{
document.write( "<p>");
document.write("<label>");
document.write("<input type='radio' class='CARadio' name='CAType' value='drop' id='CAType_0'>");
document.write("Drop</label>");
document.write("<br>");
document.write("<label>");
document.write("<input type='radio' class='CARadio' name='CAType' value='withdraw' id='CAType_1'>");
document.write("Withdraw</label>");
document.write("<br>");
document.write("<label>");
document.write("<input type='radio' class='CARadio' name='CAType' value='other' id='CAType_2'>");
document.write("Other</label>");
document.write("<br>");
document.write("</p>");
document.write("</p>");
document.write("<p>If Other Please Specify:</p>");
document.write("<p>");
document.write("<textarea name='txfdCApp' id='txtCAP'></textarea>");
document.write("</p>");
}
}
</script>
<p>Application Details:</p>
<p>
<textarea name="textarea" id="textarea" rows="10" cols="30" ></textarea>
</p>
<p>
<input name="submit" type="submit" id="submit2" formmethod="POST" value="Submit">
</p>
<p> </p>
</form>
</body>
</html>
I have only made the code for the first selection option. But the part of the code I have written in myfunc opens in another window. I want to code in a way that for every particular option the additional code opens on the same form after the end of select tag and before the additional information tag.
What am I doing wrong.
I would to suggest to place all your conditionally required fields into a div. Then use JavaScript to determine whether to show the div or not. This eliminates the needs to create HTML nodes manually, which can be messy.
You also need to consider the implications if the user picks the same option in the select list multiple times... it will keep adding nodes, which is bad.
Relevant code snippet:
<div id='extra_questions' style='display: none; background-color: #0094ff;'>
<!-- add radio buttons or whatever here -->
Question #1<br />
Question #2<br />
Etc.<br />
</div>
<script type="application/javascript">
function myfunc() {
var Appread = document.forms[0].appselect.value;
if (Appread.localeCompare("Course_Application") == 0) {
document.getElementById('extra_questions').style.display = 'block';
} else {
document.getElementById('extra_questions').style.display = 'none';
}
}
</script>
You are doing it backwards. :-)
You are writing code with document.write. Where do you think this code goes to?
(Remember that the javascript is executed when an option changes in your SELECT.)
End of document? (Which already had its tags I presume)
The right way to add "live" elements to your page is by creating new DOM elements.
It might seem daunting in the beginning, but give it a shot.
I recommend starting here (and avoid w3schools):
https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
Try this.
After the </select> tag, add this.
<option value="SA_Applications">Student Affair Application</option>
</select>
</p>
<div id="ApplicationTypeResult"></div>
Then, save this as testresult.html in the same folder.
<p><label><input type='radio' class='CARadio' name='CAType' value='drop' id='CAType_0'>Drop</label><br>
<label><input type='radio' class='CARadio' name='CAType' value='withdraw' id='CAType_1'>Withdraw</label><br>
<label><input type='radio' class='CARadio' name='CAType'>Other</label><br></p>
<p>If Other Please Specify:</p>
<p><textarea name='txfdCApp' id='txtCAP'></textarea></p>
And try this.
function myfunc() {
var Appread = document.forms[0].appselect.value;
if(Appread.localeCompare("Course_Application")==0) {
document.getElementById("ApplicationTypeResult").innerHTML = '<object type="text/html" data="testresult.html"></object>';
}
It will be easier if you use jquery by
function myfunc() {
var Appread = document.forms[0].appselect.value;
if(Appread.localeCompare("Course_Application")==0) {
$("#ApplicationTypeResult").load("testresult.html");
}
Hope this helps, please change your div id name to whatever you might need and note the pathname to whereever you might save the file.
Expected behaviour will be this, (just plain).

html dom and javascript

I'm trying to get the elements from textboxes nameBox and foodBox to be displayed in the paragraph id=message after the submit button is clicked, with the message:
“Hello <name in namebox>! We want to let you know that <food in foodbox> has 50% discount in our restaurant!”
But i can't figure out how to do that. I'm pretty sure i'm doing something (if not all) wrong but since i'm new at this i can't figure it out what.
<body>
<br>
<br>
<div>
<p id="message"></p>
</div>
Enter your name:
<input type="text" id="nameBox" value=""><br>
Enter your favorite food
<input type="text" id='foodBox' value=""><br>
<button id="submitButton">Submit</button>
<script>
var parent=document.getElementById("message");
var child=document.getElementById("nameBox");
parent.removeChild(child);
</script>
</body>
That's because parent is not the parent of child. To make it so, edit your code to put the two input elements inside the <p> tag:
<p id="message">
Enter your name:
<input type="text" id="nameBox" value=""><br>
Enter your favorite food
<input type="text" id='foodBox' value=""><br>
</p>
Here you go :
<html>
<head>
<script>
function showText(){
var name=document.getElementById("nameBox").value;
var food=document.getElementById("foodBox").value;
document.getElementById("msg").innerHTML="Hello " + name + " ! We want to let you know that has 50% discount in our restaurant! for " + food;
}
</script>
</head>
<body>
<br>
<br>
<div id="msg">
</div>
Enter your name:
<input type="text" id="nameBox" value=""/><br>
Enter your favorite food
<input type="text" id="foodBox" value=""/><br>
<input type="button" id="submitButton" onclick="showText()" value="Submit" />
</body>
</html>
You can make your alignments as you wish, try to use firebug (https://getfirebug.com/) in case of finding UI related issues. It is pretty easy to figure out what is wrong in the UI
Check your HTML. Maybe it should look like this?
<div id="message">
Enter your name:
<input type="text" id="nameBox" value=""><br>
Enter your favorite food
<input type="text" id='foodBox' value=""><br>
<button id="submitButton">Submit</button>
</div>
You can call function on clicking submit button and then change the message.
<input type="button" id="submit" value="Submit" onclick="somefunction()"/>
Here is the javascript:
function somefunction() {
var fieldNameElement = document.getElementById('message');
fieldNameElement.innerHTML = “Hello ! We want to let you know that has 50% discount in our restaurant!” ;
}
While changing the innerHTML you can add appropriate formatting tags as well.
Also you should add inputs in a table, and add border's and required formatting if required:
<table>
<tr>
<td>
Enter your name:
</td>
<td>
<input type="text" id="nameBox" value=""><br>
</td>
</tr>
<tr>
<td>
Enter your favorite food
</td>
<td>
<input type="text" id='foodBox' value=""><br>
</td>
</tr>
</table>
You can also think about using a Javascript library which provides lot of methods to make your life easy, would suggest JQUERY
Cheers !!

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>
​

Categories

Resources