1

So I have been learning the basics of the JavaScript language. So far so good. I'm practicing a lot of comparative operations to understand various calculations and outputs based on my variable definitions.

I can define 2 variables and set them. That's easy.

var variable1 = 1; 
var variable2 = 2;

I can use an if/else statement to compare the 2 variable values.

if (variable1 > variable2) {

  alert("The first variable is greater than the second.");

} else {

  alert("The second variable is greater than the first one.");

}

I understand this simple logic and how this works.

My question is, if I want a webpage user to type in 2 numbers so I can calculate them (using the above conditional statement) how do I access or define the variables that are the result of user input? So far I can only define the variables myself in a js file. How would I access user html input in javaScript to perform the same calculation?

My first assumption would be that I use the getElementById property to access the value of a textarea element in html. But I am not sure how this would store the textarea value as a variable to then be calculated. I hope this makes sense.

Thank you to those who will help me with this. I appreciate that your time is important and that this is a VERY basic question for many of you.

3
  • I don't want to post such a short answer as an answer because someone else might take the time to elaborate. var variable1 = document.getElementById('inputfield1').value; Commented May 22, 2014 at 2:29
  • This, however may not be true. "The second variable is greater than the first one." because given the clause, the second variable is greater than or equal to the first one. Commented May 22, 2014 at 2:32
  • 1
    When you are starting out, window.prompt() can be a useful crutch before learning about extracting values from HTML form input. Usage: variable1 = window.prompt("Enter a value for variable1:"); Commented May 22, 2014 at 2:36

8 Answers 8

4

View this working example

HTML

<input type="text" id="inputfield1" />
<input type="text" id="inputfield2" />
<button onclick="compare()">Compare</button>

JS

function compare(){
    var variable1 = parseInt(document.getElementById('inputfield1').value);
    var variable2 = parseInt(document.getElementById('inputfield2').value);
    if (variable1 > variable2) {
      alert("The first variable is greater than the second.");
    } else {
      alert("The second variable is greater than or equal to the first one.");
    }    
};

Just bear in mind that text inputs come back as strings. I've used parseInt() to convert to integers for this example.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. The addition of the parse conversion is extra helpful. As is the use of a function and onclick event to compare the results. I'm learning bit by bit but this helps me to string it all together. :)
I realize that this is all just educational experimentation, but if you're ever using parseInt in a real situation, make sure to read how it works first. In my answer I recommend multiplying by 1 instead. It's less likely to fail in unexpected ways (though it still might). For example: jsfiddle.net/eFkze/1
That fiddle example doesn't demonstrate parseInt() failing.
2

For example you have an HTML page:

<html>
...
<!-- comment: make sure to include your script here as this is a common mistake -->
<body>
  <input type="text" id="text1ID" />
  <input type="text" id="text2ID" />
</body>
...
</html>

In your included JavaScript, you can do this:

// getting the values:
var variable1 = document.getElementById('text1ID').value;
var variable1 = document.getElementById('text2ID').value;

// add logic to do something about the values:

if (variable1 > variable2) {

  alert("The first variable is greater than the second.");

} else {
  // fixed this according to comments
  // alert("The second variable is greater than the first one.");
  alert("The second variable is greater than OR equal the first one.");

}

Comments

1

HTML Code

<input type="text" id="ele1" name="ele1" />
<input type="text" id="ele2" name="ele1" />

For JavaScript you can use getElementById to accesses the element with the specified id

var variable1 = document.getElementById("ele1").value;
var variable2 = document.getElementById("ele2").value;

For jQuery

var variable1 =$("#ele1").val();
var variable2 = $("#ele2").val();

1 Comment

Should be $("#ele1").val(); with the # symbol.
1

I would follow nmenego's advice, but keep in mind that the values you get from text fields are inherently strings (not numbers). Javascript lets you play fast and loose with this, but this results in less than ideal results:

Consider: http://jsfiddle.net/eFkze/

alert("10" > "9")

So... you'll want to collect the values and then the simplest thing is to try and multiply them by 1. The result of that operation will fail if the value is "some non numeric thing" but will work if it's "5" or "5.5".

Comments

0

Instead of using:

var variable1 = 1;
var variable2 = 2;

use:

var variable1 = document.getElementById('inputfield1').value;
var variable1 = document.getElementById('inputfield2').value;

You'll get the value of those inputfields. But you have to ensure that those are numbers you are comparing because user might put any value other than number value that you are calculating. So you have to do some validation before comparing.

Comments

0

Try this on Chrome, it is fullly HTML5 compliance, try non number and see what happens:

<!DOCTYPE HTML>
<html>
<head>
<title>Untitled Document</title>
<script>
function compare()
{
    var variable1 = document.getElementById('firstNumber').value;
    var variable2 = document.getElementById('secondNumber').value;
    if (variable1 > variable2) {
        alert("The first variable is greater than the second.");
    } else if (variable1 < variable2)
    {
        alert("The second variable is greater than the first one.");
    }  else 
    {
        alert("They are equal");
    }
}
</script>
</head>
<body>
<form onsubmit="compare();return false;">
First Number: <input type="number" id="firstNumber" name="firstNumber" required>
Second Number: <input type="number" id="secondNumber" name="secondNumber" required>
<input type="submit" value="Submit">
</body>
</html>

Comments

0

HTML

<input id='value1' type='text' placeholder='enter value1' />
<br/>
<input id='value2' type='text' placeholder='enter value2' />
<br/>
<button id='calculate'>Calculate</button>

JavaScript

var button = document.getElementById('calculate');
button.addEventListener('click', calculate, false);

function calculate() {
    var value1 = parseFloat(document.getElementById('value1').value);
    var value2 = parseFloat(document.getElementById('value2').value);

    if (value1 > value2) {
        alert("The first variable is greater than the second.");
    } else {
        alert("The second variable is greater than or equal to the first one.");
    }
}

This example provides you what you are looking for. Also it separates HTML from JS code, where you hook click event in JavaScript code instead of HTML onclick markup.

Of course you have to take care of valid input from user, so there is not text in numeric fields, but that is another story.

You can see full running example at JSFiddle

Comments

0

Below code will first check if both the inputs are entered and if both the inputs are numbers and then proceed with the calculation. isNaN function is used to check for numbers.

HTML CODE

<input type="text" id="inputfield1" />
<input type="text" id="inputfield2" />
<button onclick="compare()">Compare</button>

JAVASCRIPT

function compare()
{
    var variable1, variable2;
    try
    {
         variable1 = parseInt(document.getElementById('inputfield1').value);
     variable2 = parseInt(document.getElementById('inputfield2').value);

     if (isNaN(variable1) || isNaN(variable2))
     {
     alert("Either or both of the inputs is not a number");
     }
     else if (variable1 > variable2) 
     {
         alert("The first variable is greater than the second.");
     } 
     else 
     {
         alert("The second variable is greater than or equal to the first one.");
     }
   }
   catch (e)
   {
        alert ('Exception Caught '+e);
   }
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.