Show a notification when the values of variables 'enter' are not the

I have a website featuring 2 text boxes, a button, and a paragraph. What I would like to do is have users input a number into textbox1, another number into textbox2, and then click the "calculate" button. Upon doing so, a statement should appear indicating whether the second number is lower, higher, or equal to the first number entered in textbox1. The code below is what I've tried, but it's not functioning as expected - it consistently returns the same result.

<input type="text" id="textbox1" value="Enter a number" onfocus="javascript:this.value='';">
<input type="text" id="textbox2" value="Enter another number" onfocus="javascript:this.value='';">
<button onclick="calculate()">Calculate</button>
<p id="demo"></p>
<script>
 function calculate(){
 var x="";
 if (textbox1 > textbox2){
  x="more than";
  }
 else if (textbox1 = textbox2){
  x="Same";
  }
 else{
  x="Lower";
  }
 document.getElementById("demo").innerHTML=x;
 }
</script>

Can anyone help me figure out why? Thank you!

Answer №1

Make sure to update your code in the following way:

<input type="text" id="textbox1" value="Enter number here" onfocus="javascript:this.value='';">
<input type="text" id="textbox2" value="Enter another number" onfocus="javascript:this.value='';">
<button onclick="calculate()">Calculate</button>
<p id="demo"></p>
<script>
 function calculate()
{
var textbox1 = parseFloat(document.getElementById('textbox1').value);
var textbox2 = parseFloat(document.getElementById('textbox2').value);
var x="";
if (textbox1>textbox2)
  {
  x="greater than";
  }
else if (textbox1==textbox2)
  {
  x="Equal";
  }
else
  {
  x="Lesser";
  }
 document.getElementById("demo").innerHTML=x;
}
</script>

The issue in the initial script was that textbox1 and textbox2 were not defined, causing a failure in execution.

Answer №2

Try out this code snippet:

function compareValues() {
    var result = "";
    if (Number(input1.value) > Number(input2.value)) {
        result = "greater than";
    } else if (Number(input1.value) == Number(input2.value)) {
        result = "equal to";
    } else {
        result = "less than";
    }
    document.getElementById("output").innerHTML = result;
}

Check out the demo:http://jsfiddle.net/KDLvJ/1

Answer №3

When you assign a value, use the single equals sign (=):

else if (textbox1=textbox2)

Make sure to compare values using double equals signs (==):

else if (textbox1==textbox2)

Also remember to specify textbox1.value and textbox1.value

Check out this jsFiddle example for reference.

Answer №4

It is crucial to remember the .value property when comparing two textboxes in the code snippet. Instead of comparing the actual DOM Objects, make sure to compare their values by modifying the line:

if (textbox1>textbox2)

to

if (textbox1.value>textbox2.value)

Answer №5

These are not just any strings, they're numbers in disguise:

// Finding the hidden digits (numbers)
var num1 = document.getElementById('number1'),
    num2 = document.getElementById('number2');

// Unveiling their true identities as numeric values
var num1Value = new Number(num1.value),
    num2Value = new Number(num2.value);

// The grand reveal
var result = '';

// Are they truly numbers? By using `new Number` and the value turning out to be
// non-numeric, we can validate it with isNaN (is Not-a-Number)
if (isNaN(num1Value) || isNaN(num2Value)){
  result = 'Invalid number(s)';
} else{
  // Let the battle of numbers begin
  if (num1Value > num2Value){
    result = 'higher';
  } else if (num2Value > num1Value) {
    result = 'Lower';
  } else {
    result = 'Equal';
  }
}

// Displaying the revelation on the screen
document.getElementById('output').innerHTML = result;

See it in action

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is your prop callback failing to return a value?

I am currently utilizing a Material UI Table component in my ReactJS project and I would like to update a state variable whenever a row is selected or deselected. The Table component has an onRowSelection prop that gets triggered each time a row is is sele ...

Run a Javascript function when the expected event fails to happen

I currently have this setup: <input type="text" name="field1" onblur="numericField(this);" /> However, I am struggling to figure out how to execute the numericField() function for the element before the form is submitted. I attempted using document ...

When I attempt to run several promises simultaneously with Promise.All, I encounter an error

My code contains a series of promises, but they are not being executed as expected. Although the sequence is correct and functional, I have found that I need to utilize Promise.all in order for it to work properly. dataObj[0].pushScreen.map(item => { ...

Enhanced capabilities for the <input> element

I am seeking to develop a component that incorporates an <input> tag and offers additional functionalities like a clear text value "X" icon or any other customized actions and markup, all while maintaining the same event bindings ((click), (keyup), e ...

Utilizing the Java Script SDK for Facebook API to Publish Actions

I've been encountering difficulties with the Facebook API. I have created an app, an object, and an action, and I'm trying to test publishing in my stream (I understand that public publishing needs authorization from Facebook, but as an administr ...

The comparison between dynamically adding elements through Javascript and hiding them using CSS

I am contemplating the advantages and disadvantages of adding elements to a page and setting display:none versus creating a function that dynamically generates the elements and appends them where needed. In my current situation, I am implementing a reply ...

Facing difficulties in resetting the time for a countdown in React

I've implemented the react-countdown library to create a timer, but I'm facing an issue with resetting the timer once it reaches zero. The timer should restart again and continue running. Take a look at my code: export default function App() { ...

Utilize JavaScript's $.post function to export PHP $_POST data directly into a file

After spending hours trying to figure this out, I've come to the realization that I am a complete beginner with little to no knowledge of what I'm doing... The issue I'm facing is related to some JavaScript code being triggered by a button ...

Adjust the maximum and minimum values on a dual thumb slider

I have implemented a two thumb range slider to define the maximum and minimum values. However, I recently discovered that it is possible for the thumbs to cross over each other - the max value can exceed the min value and vice versa. I am looking for a s ...

Struggling to incorporate JSON data and javascript functions into an HTML file

I've been struggling to create a feed from a json link and display it in separate divs within an html document. Despite multiple attempts with different approaches for three different newspaper sources, I have not been successful. I'm hoping som ...

Running Windows commands from Node.js on WSL2 Ubuntu and handling escape sequences

When running the following command in the CMD shell on Windows, it executes successfully: CMD /S /C " "..\..\Program Files\Google\Chrome\Application\chrome.exe" " However, attempting to run the same comman ...

The essential guide to creating a top-notch design system with Material UI

Our company is currently focusing on developing our design system as a package that can be easily installed in multiple projects. While the process of building the package is successful, we are facing an issue once it is installed and something is imported ...

Creating a layered effect by overlaying one image on top of another in an HTML5

Currently, I am facing an issue with drawing a level field inside my canvas. The images of the tank and enemies are being drawn underneath the field image, which is causing some problems as they should actually be moving above the field. Here is a link t ...

Could not locate module: The package path ./react is not exported from the package in E:NextAppportfolio_website-mainportfolio_website-main ode_modules ext-auth

I am encountering an issue while trying to import SessionProvider from Next-Auth. The error message that is being displayed is: "Module not found: Package path ./react is not exported from package E:\NextApp\portfolio_website-main\port ...

Adjust the size of the div to match its parent's size when resizing

Can a div be resized to match its parent's size on window resize? Here is the current HTML code: <div class="sliderContainer"> <div id="cyler"> <div class="cy1" style="background-image:url(images/Keggy_Banner_Ie.jpg); back ...

Increase in JQuery .ajax timeout not effective

My website has a process where JavaScript sends a POST request to a PHP server using the .ajax() function. The PHP server then communicates with a third-party API to perform text analysis tasks. After submitting the job, the PHP server waits for a minute b ...

Steps to display the leave site prompt during the beforeunload event once a function has finished running

While facing a challenge with executing synchronous Ajax methods in page dismissal events, I discovered that modern browsers no longer support this functionality in the "beforeunload" event. To work around this issue, I implemented a new promise that resol ...

Removing an element in Vue.js

Can someone help me with a Vue.js issue I'm having? I'm working on a quiz and I want to add a button that deletes a question when clicked. Here's what I've tried so far: deleteQuestion(index) { this.questions.splice(index, ...

Determine the identifier of the subsequent element located within the adjacent <div> using jQuery

I have a form with multiple input elements. While looping through some elements, I need to locate the id of the next element in the following div. You can find the complete code on jsfiddle $(":text[name^=sedan]").each(function(i){ var curTxtBox = $(thi ...

Error message saying 'Callback has already been invoked' returned by an async waterfall function

I'm facing an error that I understand the reason for, but I'm unsure how to resolve it. Here's a breakdown of my initial function: Essentially, I am making a get request for all URLs stored in the database and then, for each URL response, I ...