Guide to showing varied results depending on a textbox input in Javascript

In my grading system, the maximum score is 100 and it is automatically calculated based on the input provided. The total score is read-only. I also want to display a brief feedback text depending on the total score without using a submit button. For instance, if the grade is 90 or below, the feedback should be set to 'Very Good', and if it's less than or equal to 80, the feedback will be 'Good'.

function calculateTotal(){
    var scores = document.getElementsByName('qty');
    var totalScore = 0;
    for(var i=0;i<scores.length;i++){
        if(parseInt(scores[i].value))
            totalScore += parseInt(scores[i].value);
    }
    document.getElementById('total').value = totalScore;
}

function provideFeedback() {
    var overallScore = document.getElementById("total").value;
    var feedbackMessage;
    if (overallScore >= 90) {
        feedbackMessage = "OUTSTANDING";
    } else if (overallScore >= 80) {
        feedbackMessage = "VERY GOOD";
    } else if (overallScore >= 70) {
        feedbackMessage = "GOOD";
    } else {
        feedbackMessage = "Needs Improvement";
    }

    document.getElementById("feedback").value = feedbackMessage;
}
<div class="column3 tworow" style="background-color:#bbb;" align="center">
    <table id="t01">
        
        <tr>
        <td>SCORE: <input type="text" name="total" id="total" style="text-align:center;font-size:20px" onkeyup="provideFeedback()" readonly></td>
        </tr>
        
        <tr>
        <td>FEEDBACK: <input type="text" name="feedback" id="feedback" style="text-align:center;font-size:20px" readonly></td>
        </tr>
        
    </table>
</div>

I attempted to use different if/else statements in JavaScript but encountered issues with the syntax of the elseif function.

Answer №1

Your code required significant cleaning, especially with the unnecessary nesting of <th> tags. Here is a simplified and functional example: input a number, press "calculate," and see the result displayed as feedback.

function calculate() {
    var feedback = document.getElementById("total").value;
    var greeting;
    if (feedback >= 90) {
        greeting = "OUTSTANDING";
    } else if (feedback >= 80) {
        greeting = "VERY GOOD";
    } else if (feedback >= 70) {
        greeting = "GOOD";
    } else {
        greeting = "Needs Improvement";
    }

    document.getElementById("feedback").value = greeting;
}
<table class="column3 tworow" style="background-color:#bbb;" align="center">
    <tr>
        <th>TOTAL: <input type="text" name="total" id="total" style="text-align:center;font-size:20px"></th>
    </tr>
    <tr>
        <th>FEEDBACK: <input type="text" name="feedback" id="feedback" style="text-align:center;font-size:20px"
                             readonly></th>
        </th>
    </tr>
</table>
<br>
<button onclick="calculate()">Calculate</button>

Furthermore, there were multiple JavaScript errors pointed out by @Snel23.

If you would like to enhance user experience by displaying feedback instantly without the need for a separate button, follow these steps:

  • Remove the <button> element
  • Add
    <input onkeyup="calculate()">
    to the existing <input> tag

Here's an updated snippet incorporating this change:

function calculate() {
    var feedback = document.getElementById("total").value;
    var greeting;
    if (feedback >= 90) {
        greeting = "OUTSTANDING";
    } else if (feedback >= 80) {
        greeting = "VERY GOOD";
    } else if (feedback >= 70) {
        greeting = "GOOD";
    } else {
        greeting = "Needs Improvement";
    }

    document.getElementById("feedback").value = greeting;
}
<table class="column3 tworow" style="background-color:#bbb;" align="center">
    <tr>
        <th>TOTAL: <input type="text" name="total" id="total" style="text-align:center;font-size:20px" onkeyup="calculate()"></th>
    </tr>
    <tr>
        <th>FEEDBACK: <input type="text" name="feedback" id="feedback" style="text-align:center;font-size:20px"
                             readonly></th>
        </th>
    </tr>
</table>

Answer №2

At the beginning of your code, you were comparing the variable feedback in your if else statements, but then switched to comparing the variable time. Additionally, you attempted to insert HTML into a non-existent element instead of setting the value on the <input id="feedback"> element. Moreover, you tried assigning the value of the non-existent variable text.

The JavaScript code below addresses these issues:

var feedback = document.getElementById("total").value;
if (feedback >= 90) {
  greeting = "OUTSTANDING";
} else if (feedback >=80) {
  greeting = "VERY GOOD";
} else if (feedback >=70) {
  greeting = "GOOD";
} else {
  greeting = "Needs Improvement";
} 
document.getElementById("feedback").value = greeting;

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

smoothly slides into view and playfully bounces

http://jsfiddle.net/E6cUF/ The concept involves a grey box sliding left from behind a green box after the page is fully loaded, with a slight bouncing effect if possible. Update: I created a new version inspired by modifications made by others on the jsf ...

Loading Jquery Image Swapping

Is there a simpler way to change the src attribute of a group of images to match their respective title attributes? <img src="" title="images/1.png" class="images" /> <img src="" title="images/2.png" class="images" /> <img src=" ...

Is it possible for WebSockets to serve as a substitute for AJAX for handling Database requests?

I have recently made the switch on my website from using the EventSource Polling constructor to the WebSocket standard in Node.js. Originally, all backend work on my site was done with PHP, but I am now trying to transition as much as possible to WebSocket ...

`resolve() and then() taking precedence over asynchronous operations`

I recently came across a tutorial on promises that explained: const promise = new Promise((resolve, reject) => { // Perform asynchronous tasks // If successful resolve(); // If fails reject(); }); After trying to implement this, I haven't had ...

Using Angular as a template engine: A simple guide

My goal is to utilize Angular as a template engine and then pass the resulting HTML code to another library. In my template file named template.html: <div><h1><span data-ng-show="details.rs">{{details.rs}}</span></h1></di ...

Encountering an error stating "cloudinary.uploader is undefined" while attempting to delete media files from Cloudinary

I'm currently developing a web application using express and node.js. In my project, I'm utilizing cloudinary for uploading media files. While uploading and accessing media works smoothly, I'm encountering an issue with deleting images from ...

Identify scrolling action in Android web browser

Seeking a way to detect the scroll event in the Android browser (I am using version 2.1, but I need it to function on older versions as well). It feels like an impossible task! Initially, I attempted: document.addEventListener('scroll', functio ...

Newly inserted JSON component remains invisible

I am currently using express.js to create an API. My mongoose is returning a JSON object and I need to append an element to each item in the result.docs. This is how I am attempting to achieve that: for(let a in result.docs) { result.docs[a].link ...

Using template literals with Optional chaining in Javascript does not yield the expected results

Trying to implement template literal with optional chaining. type Item = { itemId:number, price: number}; type ItemType = { A:Item, B:Item }; const data : ItemType = { A:{itemId:1, price:2}, B:{itemId:2, price:3} }; let key = `data?.${variable}?.ite ...

Ways to halt streaming without shutting down the Node.js server

I am currently facing an issue with closing a Twitter stream, as it causes my server to crash and requires a restart. Is there a way to close the stream without affecting the Nodejs (express) server? Here is the error message I am encountering: file:///mnt ...

Utilizing a function to populate an attribute using .attr() in d3

I utilize .attr to generate link paths in D3, as demonstrated in Lines 42 of the live demo: link.each(function (d){}) .attr('x1', function (d) { return d.source.x; }) .attr('y1', function (d) { return d.source.y; }) .a ...

substitute a component with a different one if it is present

I'm currently working on a script that will automatically replace one element with another as soon as it is created, even when the page loads. Despite my attempts to use MutationObserver, I haven't been successful. var target = document.querySe ...

Retrieving data from the option page's localStorage using the content script

Currently attempting to develop a straightforward chrome extension, however encountering challenges when trying to access the options.html's local storage from my content script "auto.js". After researching and navigating through Chrome's convol ...

What are the steps to use the vue-text-highlight feature?

I am attempting to implement an example from the basic usage section of https://github.com/AlbertLucianto/vue-text-highlight. However, upon opening index.html in Firefox, I am only greeted with a blank page. You can find the code I am using at https://git ...

Working with multi-line HTML content within Javascript

I am currently using JavaScript to define the behavior of a button on a website. I want the button to add new HTML content to a specific part of the page, and I would like to use the MVC extension method Html.EditorFor to create this new HTML. Here is wha ...

Using JQuery to control a Bootstrap carousel and add a play and pause functionality with a Javascript function

I completed all the tasks as per the video and instructions, but encountered a problem with the button functionality. When clicking on the pause symbol, it does not change to the play symbol. However, the block is working fine. What steps should I take to ...

Display a particular element when hovered over

Is there a way to make only individual elements pop up on hover instead of all of them at once? items: [{ item: "Book", info: "Lorem ipsum", displayInfo: false }, { item: "Pen", info: "Lorem ipsum", displayInfo: false }, ...

Navigating Successful or Unsuccessful Payment Routing within the Razorpay System

Recently started exploring Payment Gateway Integration and need assistance. I am looking for guidance on redirecting a URL after successful or failed payments in Razorpay. I need JavaScript code for this purpose. I believe the handler function can be util ...

Utilizing Express to Respond with an HTML Page in Axios Request

Currently, I am utilizing an axios call to verify the existence of a JWT token. If the token exists, my goal is to display the admin panel; if not, redirect to the login page. Here is how my backend is configured: //This code represents the admin panel pa ...

What methods can be used to deeply filter in Angular using the 'filter' function?

Let's imagine I have various items stored in an array: app.controller('ItemsController', function() { this.items = [ {}, { name: 'apple', }, { ...