接受用户输入,与JSON数据匹配,并以javascript显示结果

Taking user inputs, matching with JSON data and showing result in javascript

本文关键字:并以 javascript 结果 显示 JSON 用户 输入 数据      更新时间:2023-09-26

我正在用javascript创建一个表单,要求选择他的性别(单选按钮)和职业(下拉菜单)性别:

<p>  Choose 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"/>   

职业:

<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>

我还有一个JSON数据集,按性别和收入中位数列出了职业:

例如

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
    },

点击提交按钮后,我希望用户看到以下信息:

快速编辑:代替

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

如何将报表转为

 As a (gender selected- whether man or woman) you earn $------ annually working as a (name of occupation selected) and make $------- more or less (depending on the difference) than a (gender unselected) in the same profession?

当用户点击提交按钮时?

使用underscore.js和jQuery库可以轻松实现这一点。请在此处检查所附的plunker。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.")
    })