Processing user inputs, comparing them with JSON data, and displaying the corresponding results using JavaScript

I am currently developing a JavaScript form where users are asked to select their gender (radio button) and occupation (dropdown). Gender:

<p>  Pick Your Gender:</p>
Male <input type="radio" id="gender_male" name="gender" value="male"/> 
Female <input type="radio" id="gender_female" name="gender" value="female"/>   

Occupation:

<label id= "occupation"> Choose Your Occupation: </label> 
<select> 
<option value="productiontrans">Production, Transportation, Material Moving</option>
<option value="protective">Protective Service</option>
<option value="sales">Sales</option>
<option value="services">Services</option>
<option value="transport">Transportation</option> 
</select>

In addition, I have a dataset in JSON format that displays occupations categorized by gender and median earnings:

For instance,

var jobs= 
{
  "Sheet1": [
    {
      "Occupation": "Transportation ",
      "male median earnings": 24,751,
      "female median earnings": 31,981,
      "difference in pay": -7,230
    },
    {
      "Occupation": "Services",
      "male median earnings": 24,949,
      "female median earnings": 18,228,
      "difference in pay": 6,721
    },
    {
      "Occupation": "Sales",
      "male median earnings": 81,681,
      "female median earnings": 46,801,
      "difference in pay": 34,880
    },

Whenever the submit button is clicked, the user should be presented with this information:

Replace

As a man you earn $------------ annually working as a (name of the occupation) and make $ ------ more than a woman in the same profession. 

with

 As a (selected gender - either male or female) you earn $------ annually working as a (selected occupation) and make $------- more or less (depending on the difference) than a (non-selected gender) in the same profession?

once the submit button has been pressed?

Answer №1

To easily achieve this, utilize underscore.js and the jQuery library. Refer to the plunker linked below for an example. https://plnkr.co/edit/spwDhAAoifc2B4jPdK9m?p=preview

var jobs = {
    "Sheet1": [{
        "Occupation": "Transportation ",
        "male_median_earnings": "24,751",
        "female_median_earnings": "31,981",
        "difference_in_pay": "-7,230"
      }, {
        "Occupation": "Services",
        "male_median_earnings": "24,949",
        "female_median_earnings": "18,228",
        "difference_in_pay": "6,721"
      }, {
        "Occupation": "Sales",
        "male_median_earnings": "81,681",
        "female_median_earnings": "46,801",
        "difference_in_pay": "34,880"
      }]
    }
    $('.show-message').on('click tap', function(){
      var gender = $('input[name="gender"]:checked').val()
          var occupation = $('select.occupation-input').val()
          var item = _.findWhere(jobs.Sheet1, {Occupation : occupation})
          alert("As a man you earn $"+ item.male_median_earnings +" annually working as a " + occupation +" and make $"+ item.difference_in_pay +" more than a woman in the same profession.")
    })

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

What is the method for obtaining the total number of steps taken in a day (pedometer) exclusively for the current day on the

Is there a way to retrieve the total steps count for the current day only? The tizen.humanactivitymonitor.setAccumulativePedometerListener function allows me to access the accumulativeTotalStepCount, which represents the cumulative walking and running ste ...

Selecting a HEX code from a color picker to configure three.js as a string

Recently, I've been using a color picker from jscolor.com that outputs colors in the format of FFA6A6. The challenge I'm facing is integrating this color output with three.js, which requires the color to be in the format of 0xFFA6A6. As much as I ...

Displaying multiple div elements when a button is clickedLet multiple divs be

ISSUE Hello there! I'm facing a challenge where I need to display a div when a button is clicked. The issue arises from having multiple divs with the same class, making it difficult for me to target each individual div... Image1 Image2 Desired Outco ...

Deactivate toggle effect by clicking on a different link

My existing JavaScript code changes the background color of a link when it is clicked: $(".button").click(function(){ $(this).css('background-color', '#555'); }); While this functionality works, I am looking to have the color tog ...

What is the best way to stop form submission in AngularJS when submitting the form by pressing the enter key?

I have implemented validation on my form (which consists of only two fields) but I am struggling to figure out how to prevent it from being submitted with empty data. The current flow is as follows: Upon pressing the enter key, the student's name and ...

Prevent certain dates from being selected in a designated input field

I am facing an issue with disabling certain array dates for a specific input field in a datepicker calendar. Even though I have included the script to exclude those dates, they are not getting disabled for that particular input field. html <input cla ...

Obtain the API response using a Promise.then() in AngularJS

Recently, I've been delving into AngularJS and trying to create a function that deletes a user. The goal is to have the function return a boolean value indicating whether the deletion was successful or not. Despite my best efforts, the promise always ...

Completing a form and reloading the page without including the reload in the browsing history

I am currently developing a compact web application using Flask, and I have encountered a challenging issue with navigating back to the previous page. Here are some approaches I have experimented with: Avoiding navigation away from the page - content ...

"Discovering the method to showcase content based on page number or when the 'previous' or 'next'

Here is how my Vue component looks like: <template> ... <b-col v-for="item in items" v-bind:key="item.id" cols="2"> ... <strong slot="header" class="text-dark" :title ...

What is the process of creating a new array by grouping data from an existing array based on their respective IDs?

Here is the initial array object that I have: const data = [ { "order_id":"ORDCUTHIUJ", "branch_code":"MVPA", "total_amt":199500, "product_details":[ { ...

Tips for setting up a Vue application (using vue-cli) to include nonce attributes in created script tags

My vue application, compiled using vue-cli, has a vue.config.js file structured as follows: 'use strict'; module.exports = { publicPath: `${process.env.CDN_URL || ''}/dist/`, lintOnSave: true, transpileDependencies: [], outputD ...

What is the best way to extract just the hours and minutes from a timestamp column that includes hours, minutes, and seconds in my dataset and create a new column

Is there a way to extract only the hour and minute values from a timestamp column that includes seconds in my dataset? ...

Converting JSON data retrieved from a URL into HTML format

I have a JSON output from a URL that I need to format into html. The structure of the JSON data is as follows: prtg-version "xxxxxxx" treesize 0 channels 0 name "Downtime" name_raw "Downtime" lastvalue "" lastvalue_raw "" 1 name ...

The baffling quirks of variables within a Jquery loop

Unfortunately, I'm struggling to come up with a more fitting title for my question, but I'll do my best to provide a clear explanation of my issue. Here is the code snippet I am working with: let pdfInvoice_sub_template = [ {text: '{ ...

The different types of property 'cacheLocation' do not match

I have been working on updating an old React app from JavaScript to Typescript gradually. I started by migrating the configuration file, but encountered an error when renaming it to .TS. Here is the error message: /Users/xx/yy/lulo/src/adalConfig.ts (13, ...

Retrieve the class name based on the ID of the final appearance of the div using jQuery

<div class='user user1' id='newuser'></div> <div class='user user2' id='newuser'></div> <div class='user user3' id='newuser'></div> To retrieve the class name ...

When you click on a list of links, a stylish image gallery will appear using fancybox

Can anyone lend a hand with this? I would greatly appreciate any assistance CSS <a id="fancybox" href="javascript:;">Gallery 1</a> <br /> <a id="fancybox" href="javascript:;">Gallery 2</a> <br /> <a id="fancybox" hr ...

ASP.NET MVC Action throws a 500 error when receiving invalid JSON input

Currently, I am in the process of developing an API for a partner organization to facilitate the upload of reports. The code snippet I have created for this purpose is outlined below: [Route("UploadReport"), HttpPost] public async Task<ActionResult> ...

Should the ID be utilized in a modal dialog?

When working with a modal window, I need to know how to retrieve and utilize the field id of the record in a mysql select. While I am able to display it using . , I am unsure of how to work with it using PHP. Any assistance would be greatly appreciated. ...

Code for remotely connecting to a server and starting a Node.js application called app.js via SSH

I am attempting to establish an SSH connection to two servers sequentially in order to execute the following command: sudo node app.js This is the code I am using: #!/bin/bash while read line; do ssh -i "sshtest.pem" ec2-user@$line "sudo node app. ...