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

The asynchronous ajax function fails to work properly when setInterval is activated

My issue is that only the initial execution of the updateProgress function happens while waiting for the completion of syncDNS. All subsequent calls made via setInterval remain on hold until syncDNS finishes. Can anyone explain why this is happening? $( ...

Can Vuex mapActions be utilized within a module that is exported?

Is it possible to utilize Vuex mapActions from an external module imported into a component? I am working on standardizing a set of functions in a vue.js web application. My goal is to import these functions into each component and pass necessary values f ...

Jssor's dynamic slider brings a touch of sophistication to preview upcoming images

Incorporating the jssor nearby slider to create a nearly fullscreen display. The goal is to set the opacity of upcoming images to 0.25 when they are not in the main viewport, giving the edges of the upcoming and previous slides a slight transparency. < ...

Develop an application using ASP.NET MVC that allows for returning a JavascriptResult along with a

Imagine this situation When using MVC, it is quite simple to send a Javascript code back to the client for execution public ActionResult DoSomething() { return JavaScript("alert('Hello world!');"); } On the client side, ...

What is the best way to optimize a search for objects with extensive field arrays?

Recently, I've been working with an object schema that includes an array field to store ids for objects from a separate collection. This array has the potential to contain thousands of ids. Up until now, I have been excluding this field using .select( ...

Show a different image with a matching title each time the page loads

I need help creating a JavaScript script that will display a random image from an array along with an associated title each time the page loads. Is there a way to do this without using an onload function placed in the body tag? Currently, my code relies o ...

What is the best way to format a text component so that the initial word in each sentence is bolded?

Creating a text component where the first word of the sentence is bold can be a bit tricky. The current solution may result in a messy output like "Tips: favouritevacation" where there is no space after "Tips:". This approach is not very elegant. One pos ...

Doesn't the .stop(true) function completely clear the queue as it should?

My slideshow has a hover function to pause it using .stop(true). Upon mouse exit, it should resume playing from where it left off. However, currently, when I hover over it, the animation stops and then continues until it reaches its target, pausing there a ...

Add a CSS and jQuery hover effect to display text over an image, requiring users to click twice on their mobile device

I have a bunch of panels for different categories that change the background image when hovered over, display some introductory text, and lead to a URL when clicked. However, on mobile devices, you need to tap the panel twice to activate the URL. What I&a ...

Is it possible to swap the src of the Next.Js Image Component dynamically and incorporate animations in the

Is there a way to change the src of an image in Nextjs by using state and add animations like fadein and fadeout? I currently have it set up to change the image source when hovering over it. const [logoSrc, setLogoSrc] = useState("/logo.png"); <Image ...

Updating controller variables when the route changes in AngularJS

I'm new to the AngularJS scene and I've encountered a challenge. My goal is to have the selected tab change dynamically based on the URL changes. Here's my JavaScript code: app.config(function($routeProvider, $locationProvider){ $rou ...

Using the outer ng-repeat's object property to filter nested ng-repeat items

I'm currently working on nesting two ng-repeats with two separate JSON files. The goal is to filter the second ng-repeat based on parameters from the first ng-repeat. The first JSON file, $scope.matches, includes information about each match in the W ...

Error: Access Denied - discord.js bot command cannot be executed due to lack of authorization

Every time I initiate the bot and try to execute my "ping" command, an error occurs: js:350 throw new DiscordAPIError(data, res.status, request); ^ DiscordAPIError: Missing Access at RequestHandler.execute (C: ...

Issues with sending emails through Nodemailer in a Next.js project using Typescript

I'm currently working on a personal project using Nodemailer along with Next.js and Typescript. This is my first time incorporating Nodemailer into my project, and I've encountered some issues while trying to make it work. I've been followin ...

The transformation rotation applied in CSS must not have any impact on the styling of my span and paragraph

Snippet: .details-section{ background-color: rgb(83, 83, 83); height: 200px; } .icon-container{ border: 2px solid #c49b63; width: 90px; height: 90px; transition: 0.5s ease; } .box i{ font-size: 60px; color: black; margin-top: 13px ...

Capturing and setting form element values within a Javascript Module Pattern

I'm looking to streamline my form element access using the Module pattern. The goal is to eliminate redundancy by organizing everything under a single module. How can I achieve this without having to directly call the Anonymous function within the mo ...

Using JavaScript ES6, we can access a specific array nested within a JSON array and loop through its elements by utilizing the

I have retrieved a JSON data from this link "response": [{ "id": "1", "title": "Star Wars", "project": [ "Star Wars Proj1", "Star Wars Proj2", "Star Wars Proj3", "Star Wars Proj4" ] }, { "id": "2", "titl ...

Automatically simulate the pressing of the enter key in a text field upon page load using Javascript

I am looking to simulate the pressing of the enter key in a text field when a page is loaded. Essentially, I want the text field to automatically trigger the enter key press event as if it had been pressed on the keyboard by the user. Below is an example o ...

Kendo's data-bind onclick feature functions properly on web browsers but fails to work on mobile devices

As a newcomer to Kendo and JavaScript, I may be missing something obvious... In one of my list entries, I have a simple call like this: <li style="margin: 0.5em 0 0.5em 0"> <a href="#transaction-details" data-bind="click: onB ...

Is it possible to save user inputs in a .json file for future use, and retrieve and reuse them in subsequent sessions or processes?

I am currently developing an account generator using puppeteer and I have a specific requirement for user inputs. The script prompts the user to input necessary variables, but I am interested in exploring the possibility of storing these inputs in a JSON ...