Consistently obtaining the same outcome in JavaScript, always

Is it possible to resolve this issue? I keep getting a result of less than 18 when trying numbers 1-100, even though the output should be for values under 18.

In my HTML code, there is a <p> element with id="result", an input with id="age", and a button with id="btn".

JavaScript:
let result = document.getElementById("result");
let button = document.getElementById("btn");
let age = document.getElementById("age");

function checkAge() {

if (age >= 18){
    document.getElementById("result").innerHTML = "You have successfully signed up.";
}
if (age <= 65){
    document.getElementById("result").innerHTML = "You have successfully signed up.";
}
if (age < 18){
    document.getElementById("result").innerHTML = "You are too young to sign up.";
}
if (age > 65){
    document.getElementById("result").innerHTML = "You are too old to sign up.";
}
}

Answer №1

Focus on the crucial age ranges - too young or too old - in your function to determine if a user is in the correct age group:

function checkAge() {
  if (age < 18) {
      document.getElementById("result").innerHTML = "You are too young";
  } else if (age > 65) {
      document.getElementById("result").innerHTML = "You are too old";
  } else {
      document.getElementById("result").innerHTML = "Successfully registered";
  }
}

If they are younger than 18, they are considered too young. If they are older than 65, they are considered too old. Otherwise, they can register successfully.

Ensure you are extracting a number from the "age" element, like so:

let age = parseInt(document.getElementById("age").value);

Answer №2

const result = document.getElementById("result");
const button = document.getElementById("btn");
const age = document.getElementById("years");

function checkAge() {
    let message = '';

    if (age >= 18) {
        message = "You have successfully signed up";
    } else if (age <= 65) {
        message = "You have successfully signed up";
    } else if (age < 18) {
        message = "You are too young";
    } else if (age > 65) {
        message = "You are too old";
    }

    document.getElementById("result").innerHTML = message;
}

Answer №3

The issue lies in the fact that the tests are being conducted on the variable 'god', which represents the HTML input element, rather than the actual value entered by the user.

To retrieve the value, you should use god.value

Give this a try

let = document.getElementById("rezultat");//By the way, this is not doing anything useful
let dugme = document.getElementById("btn");
let god = document.getElementById("godine");

function myFunction() {
if (god.value >= 18){
    document.getElementById("rezultat").innerHTML = "You have successfully registered";
}
if (god.value <= 65){
    document.getElementById("rezultat").innerHTML = "You have successfully registered";
}
if (god.value < 18){
    document.getElementById("rezultat").innerHTML = "You are too young";
}
if (god.value > 65){
    document.getElementById("rezultat").innerHTML = "You are too old";
}
}
<p id="rezultat"></p>
<input id="godine"/>
<button id="btn" onclick="myFunction();">Submit</button>

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

Blocking the space bar in JavaScript is a useful technique that can be

I'm in the process of developing an application and I'm looking to prevent the space bar from scrolling my page My framework of choice is VUE, and I am trying to trigger a method using an event handler However, when I attempt to call the ' ...

Prevent the hover() effect from affecting all div elements at once

I am aiming to achieve a function where hovering over a div with the "rectangle" class will display another div with the "description" class. Initially, the description div will have a display value of "none", but upon hovering, it should become visible. ...

Error: React-Redux unable to locate Redux context value while utilizing useSelector function

After creating a store and authreducer, everything was working as expected. However, when I added the useSelector in app.js, an error occurred: ERROR Error: could not find react-redux context value; please ensure the component is wrapped in a <Provid ...

Can I send a DELETE request with request body and headers using Axios?

When working with Axios in ReactJS, I am attempting to send a DELETE request to my server. In order to do this, I need to include the following headers: headers: { 'Authorization': ... } The body of the request consists of: var payload = { ...

How can I substitute a specific capture group instead of the entire match using a regular expression?

I'm struggling with the following code snippet: let x = "the *quick* brown fox"; let y = x.replace(/[^\\](\*)(.*)(\*)/g, "<strong>$2</strong>"); console.log(y); This piece of code replaces *quick* with <strong& ...

Verify if the nested arrays within the object consist of any empty elements

Take a look at the object below: { "params": { "time_to_diagnosis": [ { "field": "date_of_diagnosis", "value": "" }, { "field": "date_of_symptom_onset", "value": "2019-09-01" } ], "time ...

Node.js's module-only scope concept allows variables and functions defined within

Currently, I am attempting to create a function that can set a variable at the top-level scope of a module without it leaking into the global scope. Initially, I believed that implicit variable declarations within a module would remain confined to the modu ...

Angular.js enables the ability to display views from several partials that are loaded dynamically

My goal is to create a view composed of multiple partials that are loaded dynamically based on the content type. While I am new to angular.js, my current approach in the controller involves: $(elem).html(string_with_src); $compile(elem.contents())($scope) ...

Combining two lists in immutable.js by flattening and zipping

When faced with two immutable lists, such as: const x = [5,6,7]; const y = [x,y,z,w]; Is there a straightforward method to combine/interleave them in order to obtain: const z = [5,x,6,y,7,z,w]; ...

Adding input values to a jQuery Ajax POST request

I am currently attempting to send form values to a remote API using AJAX. The necessary information I require from the HTML form element includes the author, string, false, and true. At the moment, I have hard-coded some values but... function sendData ...

How can we best store the component's state in the URL in AngularJS?

I am working with a reusable widget that has its own state. This state includes the content of the search bar (2), one or more select boxes (1), and the tree where the user can pick the currently active element (3). My goal is to create a locationManager ...

Unable to render properly after saving to Firebase

Currently, I am working on developing an express app that creates a Google map using geo coordinates extracted from photos. My goal is to utilize Firebase for storing data related to the images. While my code is functioning properly, I encountered an issue ...

Is there a way to search through a list and apply filters based on parameters found within a nested object?

I have a list that needs to be filtered based on parameters from advancedSearchFilters, which contains nested objects. The goal is to return a list that matches all or any of the specified parameters. const list = [ { additionalPrices: 0, clien ...

Crushing jQuery's Sortable/Droppable

Having a little issue here. I want to be able to toggle the sortable plugin's behavior by clicking a button - basically switching between sort mode and view mode. I've attempted to achieve this with the following code: function enterSortMode(){ ...

Struggling to generate an HTML table using JSON data

Struggling with generating an HTML table from JSON data, I'm inexperienced and having trouble with the logic. The JSON data I have needs to populate a complex dynamic HTML table. The design of the table is intricate, making it challenging for me to i ...

Getting the length of child elements in Angular using ngFor loop

Can anyone help me figure out how to check the length of a child element in my Angular *ngFor loop? I am fetching data from a real-time firebase database. What am I doing wrong? Here is the code snippet I am using: <div *ngFor="let event of events"> ...

The functionality of php.js is compromised

I've been attempting to integrate php.js into my scripts, but have encountered a problem. I debugged a function and loaded it onto a single page containing only jQuery and php.js, yet it is still not functioning properly. <script src="http://code. ...

When utilizing a script to deliver a true or false response for jQuery's .load() function

Currently, I have found myself delving deep into jquery to manage the ajax requests in my web applications. Specifically, I am working on a bidding system in PHP that heavily relies on mod_rewrite. Using jQuery with a confirm dialog, I send an Ajax request ...

Puppeteer with Typescript: Encountering issues during the transpilation process

The issue stems from the fact that I am unable to use Javascript directly due to Firebase Functions Node.JS version lacking support for Async/Await. As a workaround, I have converted the code into Typescript and am currently attempting to transpile it to c ...

Could there possibly exist a counterpart to .cloneNode?

I'm currently working on a recipe website submission form, and I've successfully implemented code that allows me to add more ingredients dynamically. addIngredientsBtn.addEventListener('click', function(){ let newIngredients = ingre ...