What is the best way to ensure that a status is updated only when needed in a JavaScript code?

Recently, I've been working on a project to develop a 5th Edition D&D Character Generator App (I know, nerdy but fun!). One challenge I'm facing is how to ask specific questions based on the character's level without repeating all previous questions. For instance, if a character reaches level 1 as a Ranger, the app should inquire about favored terrain and enemies. When the character advances to level 2, it should only ask the new question for that level in addition to updating existing information. How can I achieve this seamless transition of updating information with each level progression?

I believe solving this issue will also help address how to update experience points without redundancy. If not, that will be my next hurdle to tackle.

Your insights would be greatly appreciated!

Take a look at a snippet of the code related to this:

if (level >= 1) {
            var favTerrain1 = prompt("Name your favorite terrain.");
            var favEnemy1 = prompt("Name your favorite enemy type or 2 humanoid races. (If you choose the latter, please separate with a comma.)");
            document.getElementById("level1").innerHTML = "<h4><b> Favored Terrain: </b>" + favTerrain1 + "<br><b>Favored Enemy(Enemies): </b>" + favEnemy1 + "</h4>";
        }
        if (level >= 2) {
            var lv2 = +prompt("Select a fighting style: 1. Archery 2. Defense 3. Dueling 4. Two-Weapon Fighting");
            var level2;
            switch(lv2) {
                case 1:
                    level2 = "<b>Archery</b> You gain +2 bonus attack rolls you make with ranged weapons.";
                    break;
                case 2:
                    level2 = "<b>Defense</b> While wearing armor, you gain a +1 bonus to armor class.";
                    armorClass = armorClass + 1;
                    break;
                case 3:
                    level2 = "</b>Dueling</b> When wielding a melee weapon exclusively, a +2 bonus applies to damage rolls with that weapon.";
                    break;
                case 4:
                    level2 = "<b>Two-Weapon Fighting</b> During two-weapon combat, you can add your ability modifier to the second attack's damage.";
                    break;
                }
            } else {
                level2= " ";
            }

The current setup prompts questions for both level 1 and level 2 upon upgrading from 1 to 2.

Answer №1

Creating your character is like crafting an object in a traditional way: as your character levels up, they gain new attributes.

To streamline the user experience by only asking necessary questions, you can use the hasOwnProperty function to check if the player object already possesses certain properties at that level.

For example:

var player = new Object();
player.favoredTerrain = "jungle";

if (!player.hasOwnProperty('favoredMount')){
    //code to prompt for favored mount
};

if (!player.hasOwnProperty('favoredTerrain')){
    //code here won't run because favored Terrain is already set!
};

Many frameworks simplify this process for handling multiple values, such as Angular's ability to test if a value is populated and then hide/show questions accordingly. Alternatively, JQuery makes it easy to select and hide sections of questions based on answered responses. As you asked specifically about JavaScript, I provided a more basic approach.

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

Can a JavaScript callback be transmitted via JSON?

Is there a way to pass a callback function via JSON instead of using a function object? window.onpopstate = function(e) { var state = e.state; switch(state['method']) { case 'updateFields': updateFields(sta ...

Toggle the visibility of table rows based on a specific class using a checkbox

I am currently working on a code that displays the results of a query in a table format. I would like to have the ability to click on certain elements to show or hide them. I know this can be achieved using toggle and CSS, but I keep encountering obstacles ...

LESS: mastering the dumpLineNumbers function

I'm relatively new to LESS and I have a question regarding the dumpLineNumbers property within the less JavaScript object. Despite adding it to my html file, I am unable to detect any changes in the browser output or debugging tools. Can someone expla ...

Exploring AngularJS testing using Protractor's browser.wait() method

In the process of developing an automated test suite for an AngularJS application using Protractor, I have reached a point where I no longer need to manually pause the script at each step with browser.pause(). Now, I want to let the script run through to c ...

"Exploring the various configurations for session handling in NodeJs

I am trying to implement a login system using the express-session module. I'm unsure if I have set everything up correctly, especially when it comes to the secret option. Currently, my initialization code for express-session looks like this: app.use( ...

In JavaScript, adding elements within a loop does not impact the array's contents outside of the loop

I am struggling with maintaining the content of an array while pushing items onto it inside a loop. Even though the array displays correctly during each iteration, once outside the loop, all information is lost. var result = []; users.find({}, { ...

Adjust the class based on the model's value in AngularJS

items = {'apple', 'banana', 'lemon', 'cat', 'dog', 'monkey', 'tom', 'john', 'baby'} html <div class="variable" ng-repeat="item in items">{{item}} </div> ...

Loop through a JSON object using a sequence of setTimeout() functions

After running another function, I have retrieved a JSON object stored in the variable 'json_result'. My objective is to log each individual JSON part (e.g. json_result[i]) after waiting for 5 seconds. Here was my initial attempt: for (let key ...

The image selection triggers the appearance of an icon

In my current project, I am working on implementing an icon that appears when selecting an image. The icon is currently positioned next to the beige image, but I am facing difficulties in making it disappear when no image is selected. Below are some image ...

Embark on the journey of incorporating the Express Router

My Nodejs server is set up with router files that use absolute routes for the HTTP methods, such as /api/users/all. // /routes/user.routes.js module.exports = (app) => { app.use((req, res, next) => { res.header( "Access-Control-All ...

What is the best way to establish a client.js file for socket.io in Node.js?

I am looking to separate the client script from the index.html file in the chat application example found at https://socket.io/get-started/chat/. Currently, I am facing an issue where the message "a user connected" is not appearing when I refresh the webpa ...

Updating the background of a div in HTML through the power of JavaScript

I am having trouble changing the background of a DIV. I believe my code is correct, but it doesn't seem to be working. I suspect the error lies with the URL parameter, as the function works without it. Here is my code: <script language="JavaS ...

The UseEffect hook continues to run even if the dependency (router.query) remains the same

useEffect(() => { console.log('applying filter'); const updatedFilters = { status: { values: { label: router.query.status, value: router.query.status }, }, // Add additional filter properties here... }; ...

The request has encountered a 400 bad request error when using

I am encountering an issue with my web application. The frontend is built using React, the backend uses NodeJS, and the database is MongoDB. I have successfully implemented a registration form that posts data to the Node JS server via Axios and interacts ...

"Efficiently handle multiple instances of the same name using AJAX, JavaScript

I have a PHP-generated multiple form with HTML inputs containing IDs and NAMEs. I am struggling to capture all this information. When I click the "Done" button, everything is marked as completed due to the button names. <?$command = "SELECT * FROM exam ...

Integrating the feature of pasting Excel data directly into a Django form

My current Django form consists of a table with N rows and 12 columns of textboxes, allowing users to fill out the form one textbox at a time: [________][________][________][________][________][________][________][________][________][________][________][_ ...

Retrieving POST data in Ajax requests

I am currently using an ajax-based commenting system. This system is set up to create a div section for comments and a reply box through a php loop, which results in the form being duplicated multiple times. How can I ensure that the variable 'parent ...

Building secure and responsive routes using next.js middleware

After setting up my routes.ts file to store protected routes, I encountered an issue with dynamic URLs not being properly secured. Even though regular routes like '/profile' were restricted for unauthenticated users, the dynamic routes remained a ...

"Step-by-step guide on how to upload an image with precise dimensions

When using this code, I am attempting to upload only images that are the size of 512X512. However, I keep getting an error message saying "not a valid size of 512X512" even when selecting the correct image size. I am currently working on the code below an ...

Execute a function within a different function once the ajax call has been completed

There's an issue with the timing of my function that runs inside another function. It seems like sometimes the ajax call to the server isn't completed before the function is called. function obtainPlans(row, user, id, type) { $.get( "/ ...