Failure to Present Outcome on Screen

Seeking assistance! I attempted to create a mini loan eligibility web app using JavaScript, but encountered an issue where the displayed result did not match the expected outcome upon clicking the eligibility button.

Here is the HTML and JavaScript Code I used:

 


let Amount = document.querySelector("#amount").value;
let Duration = document.querySelector("#years").value;
let amt = parseInt(Amount);
let dura = parseInt(Duration);
let Message = document.querySelector("#result");
//const Income =  parseInt(Amount.value);
//const Years  = parseInt(Duration.value);
function eligibility(){
if(amt < parseInt(50000) ){
    Message.textContent = "Please! You're not eligible for the loan";
   // console.log('Try again')
} else if(amt >= parseInt(50000) ) {
    Message.textContent = "Please Fill the form below and apply"
  //  console.log('Please Fill the form below and apply')
}
}
<html>
<form action="" role="form">
                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon">
                            <span class="glyphicon glyphicon-plus"></span>
                            </span>
                            <input type="number" class="form-control" placeholder="Income"  id="amount" required  />
                        </div>
            
            
            
                    </div>
                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon">
                            <span class="glyphicon glyphicon-time"></span>
                            </span>
                            <input type="number" class="form-control" placeholder="Duration" id="years"  required  />

                        </div>
                    </div>


<button type="" class="btn btn-primary btn-block"  onclick="eligibility()">Check Eligibility</button>
  
                    <div id="result">
                        
                    </div>

                </form>
        
        </html>

Answer №1

The key issue identified was the necessity to declare input values within the function being called on button click. Failure to do so would result in all values defaulting to null upon page load.

I have made modifications to your code and provided comments for clarity. Hopefully, this brings some assistance

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>

<html>
<form action="" role="form">
                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon">
                            <span class="glyphicon glyphicon-plus"></span>
                            </span>
                            <input type="number" class="form-control" placeholder="Income"  id="amount" required  />
                        </div>
            
            
            
                    </div>
                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon">
                            <span class="glyphicon glyphicon-time"></span>
                            </span>
                            <input type="number" class="form-control" placeholder="Duration" id="years"  required  />

                        </div>
                    </div>


<button type="" class="btn btn-primary btn-block"  onclick="eligibility()">Check Eligibility</button>
  
                    <div id="result">
                        
                    </div>

                </form>
        
        </html>
<script type="text/javascript">


//const Income =  parseInt(Amount.value);
//const Years  = parseInt(Duration.value);



function eligibility(){
    //You need the declare these values inside the function (getting them globally will only get the value they are when page loads up)
    let Amount = document.querySelector("#amount").value;
    let Duration = document.querySelector("#years").value;
    let amt = parseInt(Amount);
    let dura = parseInt(Duration);
    let Message = document.querySelector("#result");
    if(amt < 50000){
        Message.innerText = "Please! You're not eligible for the loan";
       // console.log('Try again')
    }
    //Change this else-if to just an else since you are just checking for the exact opposite of your if statement
    else{
        Message.innerText = "Please Fill the form below and apply"
      //  console.log('Please Fill the form below and apply')
    }   
}

//Prevent form from submitted or else page will reload and no message would be shown
document.querySelector('form').addEventListener('submit', (e)=>{
    e.preventDefault();
});

    
</script>
</html>

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

Tips on adding line breaks after periods that are not at the end of a sentence in HTML text nodes with regular expressions

Looking to craft a regex that can identify all periods not enclosed in quotes and not followed by a '<'. This is for the purpose of converting text into ssml (Speech Synthesis Markup Language). The regex will be utilized to automatically inse ...

sharing data between two node.js servers using http

I am currently working on integrating two node.js/express servers that communicate with each other using HTTP. One of the servers, known as server A, is responsible for handling file upload requests from the browser. My goal is to seamlessly transfer any u ...

The jQuery ajax request was unsuccessful in connecting to the remote server

I've tried researching and troubleshooting, but I still can't figure out why the Ajax code is not functioning correctly. Here is my JavaScript code: $(document).ready(function(){ $("#tform").submit(function() { var varUserName ...

Having problems with loading @font-face in Ionic Framework Android app build?

While working on an app in Ionic Framework, I encountered a peculiar issue. https://i.stack.imgur.com/xk8uD.png In my Ionic Framework application, I am importing @font-face and running the app on an Android device (Galaxy SIII). Strangely, the font (Mont ...

Guide on how to showcase the template by leveraging the roomList information with ngTemplateOutlet in Angular

TS roomList = [{ name: 'Room2' }] HTML <div class="Layout-body"> <ng-container *ngFor="let dt of roomList; index as i" [ngTemplateOutlet]="Room1" [ngTemplateOutletContext]="{ data: dt, i: i }&qu ...

Enhancing Your WordPress Menu with Customized Spans

I have a WordPress menu structured like this: <div id="my_custom_class"> <ul class="my_custom_class"> <li class="page_item"><a href="#">page_item</a> <ul class='children'> <li class="page_item chil ...

Encountering an issue while attempting to implement Redux Toolkit alongside the MUI ToggleButtonGroup component

The error message initially started as: Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. When I attempted to update the Redux state using a dispatcher, the handleChange function suddenly showed an e ...

Having trouble appending a new attribute to the Mongoose output

In my Nodejs server application, I am working with a userDetail document that contains all the relevant user information. Additionally, I have a login document that stores the time of the first login, which I need to incorporate into the userDetails result ...

What strategy should be employed to ensure that Javascript is operational upon completion of page loading?

I'm facing a challenge with running my JavaScript on my ASP.NET webform page. It seems like the elements are not fully loaded when the script runs, which could be causing issues. How can I use jQuery to ensure that my script is placed at the bottom of ...

Alert: Refs cannot be assigned to function components. Any attempt to access this ref will result in failure. Have you considered using React.forwardRef()? displayed in the @Mui Component

Is anyone familiar with this particular component? <Controller control={control} {...register("DOB", {})} render={({ field }) => ( <LocalizationProvider dateAdapter={AdapterDayjs}> <DatePicker ...

What are the best practices for handling dynamic content internationalization in Angular?

According to Angular.io, the i18n tag is used to mark translatable content. It should be placed on every element tag that requires translation of fixed text. Now, what if we have an element with dynamic content? For example, consider a table displaying a ...

Trouble with Flex 3 styles not fully applying to dynamically generated tabs within a TabNavigator

When using ActionScript to dynamically create a tab, I noticed that the style is applied to the skins but not to the text of the newly created tab until I click on another tab and then go back to it. ActionScript private function clickAddTabHandler(event ...

Utilizing Angular 2+ to effectively manipulate the HTML Document Object Model with JavaScript in order to execute scripts

I'm facing an issue with inserting a script into my Angular project that has a specific format. <script type="text/javascript" src="https://s3.tradingview.com/external-embedding/embed-widget-events.js"> { "width": "510", "height": "600", "impo ...

Can you provide a method for verifying an 'undefined' variable in AJAX queries?

How can we elegantly check if a variable is undefined in JavaScript? $.ajax({ type: method, url: url, success: function (data) { if (form != null || form != undefined){ data = $(form).serialize(); } var json ...

Having trouble aligning two divs on the same line and adjusting the controls to expand their width when there is extra space

I am currently creating an application using React and Material UI, incorporating the autocomplete control feature. Take a look at the code sandbox I have set up. Here are some concerns: I am aiming to have two autocomplete controls displayed on the same ...

Angular 8 combined with Mmenu light JS

Looking for guidance on integrating the Mmenu light JS plugin into an Angular 8 project. Wondering where to incorporate the 'mmenu-light.js' code. Any insights or advice would be greatly appreciated. Thank you! ...

Be warned: Babel has detected a duplicate plugin or preset error

Currently, I am enrolled in a React course on Frontend Masters. As part of the course, we were tasked with modifying the Babel config to allow state instantiations like: state = {index: 0} in class components. However, when I executed the command: npm i ...

Round Loading Animation in CSS

I spent hours scouring the internet for a solution on how to create basic CSS circle shape loaders, but couldn't find anything straightforward. I am working on a special website project that requires displaying survey results in dynamic percentages th ...

Could someone provide a detailed explanation of exhaustMap in the context of Angular using rxjs?

import { HttpHandler, HttpInterceptor, HttpParams, HttpRequest, } from '@angular/common/http'; import { Injectable } from '@core/services/auth.service'; import { exhaustMap, take } from 'rxjs/operators'; import { Authe ...

Ways to retrieve the parent DIV's width and adjust the child DIV's width to match

Attached is my question with the HTML and a screenshot. Within a DIV container (DIV with ID=ctl00_m_g_a788a965_7ee3_414f_bff9_2a561f8ca37d_ctl00_pnlParentContainer), there are two inner DIVs - one for the left column TITLE (DIV ID=dvTitles) and the other f ...