Using Javascript to compare two input numbers in HTML? - javascript

I am using Notepad++ to create a simple web page where a user types in two numbers into a text box, and then presses a button. When they press the button something comes up that tells them whether the first or second number is greater. I have the following code but cant get anything to come up. Does anyone know whats wrong?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>Assignment 10 Form</title>
<script type="text/javascript">
function greaterNum(){
var value1;
var value2;
value1 = document.First_num.value;
value2 = document.last_num.value;
if (value1 > value2){
alert('Value 1 is greater than value 2');
document.body.style.background = "orange";
}
}
</script>
<style type="text/css">
body{background-color: #40FF00;
margin-left: auto;
margin-right: auto;
width: 60%;
}
#container{
border: 2px solid yellow;
padding: 20px;
}
</style>
</head>
<body>
<h1>Assignment 10</h1>
<div id="container">
<div class="Num">
<form>
<label class="label1">Enter Value 1:</label>
<input type="text" name="First_num" value=" " />
<label class="label1">Enter Value 2:</label>
<input type="text" name="last_num" value=" " />
<br/>
<input type="button" value=" Which number is greater? " onclick="greaterNum();" />
</form>
</body>
</html>

Values from inputs are retrieved as strings, you need to convert it to number. Try this:
value1 = +document.First_num.value;
value2 = +document.last_num.value;
Also, try to be consistent when naming your input, why caps for one and lowercase for the other?

You may need to use:
value1 = document.getElementById("First_num").value;
However, this only works if you assign the elements id attributes:
<input type="text" id="First_num" name="First_num" value=" " />
Otherwise, use the getElementsByName.
Hope this helps!!

Convert to floats.
value1 = parseFloat(document.First_num.value);
value2 = parseFloat(document.last_num.value);

Html is a string, not a value. You need to parse it in someway.
EDIT:
The problem seems to be grabbing the values, change it to getElementById and it works fine:
http://jsfiddle.net/fHtZU/10/
HTML
<h1>Assignment 10</h1>
<div id="container">
<div class="Num">
<form>
<label class="label1">Enter Value 1:</label>
<input type="text" id="First_num" name="First_num" />
<label class="label1">Enter Value 2:</label>
<input type="text" id="last_num" name="last_num" />
<br/>
<input type="button" id="clickme" value="Which number is greater?" onclick="greaterNum()" />
</form>
js
function greaterNum(){
var value1;
var value2;
value1 = document.getElementById("First_num").value;
value2 = document.getElementById("last_num").value;
if (value1 > value2){
alert(value1 - value2);
document.body.style.background = "orange";
}
}

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;
}

Function keeps returning NaN, tuition calculator

I can't seem to get my function right.....It's a tuition calculator. At this point the residency and semesters don't matter. It's just credits * credit cost, but it keeps returning NaN.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Greendale Community College</title>
<script type="text/javascript">
/* <![CDATA[ */
/* ]]> */
var numCredits = 0;
var creditCost = 302;
var instate = 0;
var outstate = 0;
var international = 0;
var tuitionCost = number;
function calcTuition(numCredits, creditCost) {
var tuitionCost = numCredits * creditCost;
document.write("Your tuition cost is $" + tuitionCost);
}
</script>
</head>
<body>
<p><center><font face="impact" font size="200" color="green">Greendale Community College</font></center></p>
<center><img src="greendale.jpg" alt="greendale" width="512" height="256"/></center>
<h1><center>Tuition Calculator</center></h1>
<form name="calculator" action="" method="get">
<h2>Semester</h2>
<h3>(choose a semester)</h3>
<input type="radio" name="semesterFall"/> Fall 2018 <br />
<input type="radio" name="semesterSpring"/> Spring 2018 <br />
<input type="radio" name="semesterSummer"/> Summer 2018 <br />
<h2>Residency</h2>
<h3>(choose your residency)</h3>
<input type="radio" name="instate" /> In-State <br />
<input type="radio" name="outstate" /> Out-of-State <br />
<input type="radio" name="international" /> International <br />
<h2>Credits</h2>
<h3>(enter your number of credits)</h3>
<input type="text" name="numCredits" size="2" onchange="calcTuition(numCredits, creditCost)"/> Credits <br />
<input type="button" name="tuition" onclick="window.alert(calcTuition(numCredits, creditCost))" value="Calculate your Tuition" />
</form>
</body>
</html>
I took a look at what's going on and it looks like you're trying to call numCredits when it is not a valid number. The exact type of it is $[object HTMLInputElement]. Addition between an HTMLInputElement and Integer is undefined behavior and as a result the value that you obtain is NaN.
One possible solution is using the document.getElementbyId method to return the actual element and then you can perform any operation on them.
PS: You should try and debug your own functions, you mentioned you're new to this but it would be great to set up some print statements or use an interactive debugger to see exactly where the problem is occurring. This way you can troubleshoot it and understand the problem at the same time.
<script type="text/javascript">
var c_amount = 302;
function calcu_Tuition(Credits, c_amount) {
//var Credits
var Credits = document.getElementById("Credits").value //it will get the value of Credits text box and be transfer to Credits variable.
var tuition = 0;
var tuition = Credits * c_amount;
document.write("Your tuition cost is $" + tuition);
}
</script>
<body>
<h2>Credits</h2>
<h3>(enter your number of credits)</h3>
<input type="text" id="Credits" size="2" onchange="calcu_Tuition(Credits, c_amount)"/> Credits <br>
<button id="tuition" onclick="calcu_Tuition(c_amount)">Calculate your Tuition"</button>
</form>
</body>

html How can I get multiple instant results from single calculation

Is it possible to get a dozen results from this single basic calculation? I have two output textboxes in the sample code; how can I get these two fields to work?
<!DOCTYPE html>
<html lang = "en">
<head>
<title> multiple results calculation </title>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<link rel="style" href="css/main.css" type"text/css"/>
<!-- I need multiple results from single calculation!
<script type="text/javascript">
function sum()
{
var width = document.multiple results.width.value;
var height = document.multiple results.value;
var sum = parseInt(width) * parseInt(height) /144;
document.getElementById('Calculate').value = sum;
document.getElementById("results1").readOnly=true;
document.getElementById("results2").readOnly=true;
var result1= $1.99;
var result2= $2.99;
document.getElementById('Calculate').value = sum * result1;
document.getElementById('Calculate').value = sum * result2;
}
</script>
-->
</head>
<body>
<div>
<H2> Multiple instant results from single calculation</h2>
<p> the goal eventually is to have about a dozen results from this single calculation
</div>
<form name="multiple results">
<label for="width"> Width: </label>
<input type="number" <id="width" maxlength="4" size="10" value=""/>
<label for="height"> Height: </label>
<input type="number" <id="height" maxlength="4" size="10" value=""/>
<input type="button" name="button" value="Calculate" onClick="sum"/>
<div>
<label for="result1"> Result1: $ </label>
<input type="number" id="result1" name="result1"/>
<label for="result2"> Result2: $ </label>
<input type="number" id="result2" name="result2"/>
</div>
</form>
</body>
</html>
I found a solution by removing the first document.getElementById('Calculate').value = sum;, changed the remaining getElementById's and input type's to result and result2 also added the missing value="" to input, not necessary but renaming Id's helped me

Posting JS variable from HTML form

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>

How might I calculate the sum of radio button values using jQuery?

I am trying to create a form with many groups containing many radio buttons. When the user selects a button, I would like to calculate the sum of each selected radio button value and show this sum to the user.
I have found a plugin for jQuery which will do the calculation, this plugin use the name attribute of the buttons to calculate. For example, it will sum the values of all buttons which have the name sum.
So far, I have tried two ways of setting this up: in the first method, I create a hidden field for each group to hold the sum of the selected values inside it, this hidden field gets the value but the problem is that the total value will not update when a user selects a button. My code looks like this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script src="jquery.js" type="text/javascript">
</script>
<script src="calc.js" type="text/javascript">
</script>
<script src="calc_f.js" type="text/javascript">
</script>
<script type="text/javascript">
function DisplayPrice(price){
$('#spn_Price').val(price);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<input type="hidden" id="spn_Price" name="sum" value="">
<br>
<input id="rdo_1" type="radio" value="159" name="price" onclick="DisplayPrice(this.value);">
<br>
<input id="rdo_2" type="radio" value="259" name="price" onclick="DisplayPrice(this.value);">
<br>
<input type="text" name="totalSum" id="totalSum" value="" size="2" readonly="readonly">
</form>
</body>
</html>
In this code, the input tag with the name totalSum is where the value will update, but it won't update when changing the buttons.
As I said before, the reason why I use a hidden field is to hold each group's subtotal. It has the name sum, which indicates to the plugin that it should be added to others.
I dont know if this is the right way to do this, i have tried to change the name attribute of the buttons when user click them to sum but that didn`t work either!
Here is plugin address : http://www.pengoworks.com/workshop/jquery/calculation/calculation.plugin.htm
How can I do this ?
Plugin schmugin. Get rid of your onclick and try this:
$("input[type=radio]").click(function() {
var total = 0;
$("input[type=radio]:checked").each(function() {
total += parseFloat($(this).val());
});
$("#totalSum").val(total);
});
Untitled Document
<script type="text/javascript">
function DisplayPrice(price){
var val1 = 0;
for( i = 0; i < document.form1.price.length; i++ ){
if( document.form1.price[i].checked == true ){
val1 = document.form1.price[i].value;
}
}
var val2 = 0;
for( i = 0; i < document.form2.price2.length; i++ ){
if( document.form2.price2[i].checked == true ){
val2 = document.form2.price2[i].value;
}
}
var sum=parseInt(val1) + parseInt(val2);
document.getElementById('totalSum').value=sum;
}
</script>
</head>
<body>
Choose a number:<br>
<form name="form1" id="form1" runat="server">
<br>
<input id="rdo_1" type="radio" value="159" name="price" onclick="DisplayPrice(this.value);">159
<br>
<input id="rdo_2" type="radio" value="259" name="price" onclick="DisplayPrice(this.value);">259
<br>
</form>
Choose another number:<br>
<form name="form2" id="form2" runat="server">
<br>
<input id="rdo_1" type="radio" value="345" name="price2" onclick="DisplayPrice(this.value);">345
<br>
<input id="rdo_2" type="radio" value="87" name="price2" onclick="DisplayPrice(this.value);">87
<br>
</form>
<input type="text" name="totalSum" id="totalSum" value="" size="2" readonly="readonly">
</body>
The code above will dinamically sum the checked values from both groups.
parseInt will convert to integers. Use parseFloat otherwise.

Categories