如何使用Json文件填充输入字段?

时间:2019-06-29 19:01:52

标签: javascript jquery html json

我正在尝试自动填充html表单字段。根据用户在第一个字段中选择的内容,其他输入字段将自动填充。我能够通过我的朋友获得相关功能的代码(获取json数据,从json数据创建下拉列表)。这是该代码的链接 enter code herehttps://jsfiddle.net/r4zuy7tn/1/”。我也添加了有问题的代码。

但是不幸的是,在他的代码中,他使用了动态输入字段。而且我不喜欢使用动态字段。因此,我尝试编辑代码的某些部分(我是通过朋友认识的),以便可以使此代码自动填充手动创建的输入字段中的值,而不是创建动态输入字段并填充它们。但这失败了,因为我对编码不够了解。

有人可以帮我完成这项任务吗? 我只需要在代码(javascript)中添加一些不同的功能即可填充手动创建的输入字段,而不是创建动态字段。 任何帮助将不胜感激...

// define the headings here, so we can access it globally
// in the app
let headings = []

// appending the created HTML string to the DOM
function initInputs(headingList) {
  jQuery(".fields").append(createInputsHTML(headingList))
}

// the HTMLT template that is going to be appended
// to the DOM
function createInputsHTML(headingList) {
  let html = ''
  headingList.forEach(heading => {
    if (heading !== 'Company') {
      html += `<label for="${heading}">${heading}: </label>`
      html += `<input id="${heading}">`
      html += '<br>'
    }
  })

  return html
}

// receiving data
// this data arrives later in the app's lifecycle,
// so it's the best to return a Promise object
// that gets resolved (check JS Promise for more information)
function getJSON() {
  return new Promise(resolve => {
    jQuery.get("https://cors-anywhere.herokuapp.com/www.coasilat.com/wp-content/uploads/2019/06/data-1.txt", function(data) {
      resolve(JSON.parse(data))
    });
  })
}

// processing raw JSON data
function processRawData(data) {
  return new Promise(resolve => {
    const companyData = []
    // creating data array
    // handling multiple sheets
    Object.values(data).forEach((sheet, index) => {
      sheet.forEach((company, i) => {
        companyData.push({ ...company
        })
        // create headings only once
        if (index === 0 && i === 0) {
          Object.keys(company).forEach(item => {
            headings.push(item.trim())
          })
        }
      })
    })
    resolve(companyData)
  })
}

$(async function() {

  let lists = [];

  function initAutocomplete(list) {
    const thisKey = 'Company'
    $("#company").autocomplete('option', 'source', function(request, response) {
      response(
        list.filter(item => {
          if (item[thisKey].toLowerCase().includes(request.term.toLowerCase())) {
            item.label = item[thisKey]
            return item
          }
        })
      )
    })
  }

  $("#company").autocomplete({
    minLength: 3,
    source: lists,
    focus: function(event, ui) {
      // the "species" is constant - it shouldn't be modified
      $("#company").val(ui.item.Company);
      return false;
    },
    select: function(event, ui) {
      // handling n number of fields / columns
      headings.forEach(heading => {
        $('#' + heading).val(ui.item[heading])
      })
      return false;
    }
  });

  // starting data download, processing and usage
  getJSON()
    .then(json => {
      return processRawData(json)
    })
    .then(data => {
      // just so we see what data we are using
      console.log(data)
      // make the processed data accessible globally
      lists = data
      initAutocomplete(lists)
      initInputs(headings)
    })

});

// this is how you get values form the form
document.getElementById('btnListValues').addEventListener('click', function(e) {
  formGetValues('frm1')
})
// this is how you reset the form
document.getElementById('btnResetForm').addEventListener('click', function(e) {
  formSetValues('frm1', '')
})

function formSetValues(formId, val) {
  const formEl = document.getElementById(formId).elements
  for (let i = 0; i < formEl.length; i++) {
    formEl[i].value = val
  }
}

function formGetValues(formId) {
  const formEl = document.getElementById(formId).elements
  for (let el of formEl) {
    console.log(el.value)
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
<div class="ui-widget">
  <form id="frm1">
    <label for="company">Company: </label>
    <input id="company"><br />
    <div class="fields"></div>

<!-- below given input fields are those ones which i wanted to prefill, rather than creating dynamic fields. but my friend added that kind of function in javascript which firstly creates dynamic input fields and then populate them automatically.....

 
 
1) PE Ratio
    <input type="number"  id="PE" /><br>
    2)Price/Book 
     <input type="number"  id="PB" /><br> 
    3)ROCE
    <input type="number" id="ROCE" /><br>
    4) Sales Growth
     <input type="number" id="SG" /> <br> 
    5) NPM 
  <input type="number" id="NPM" /><br>
  6) ROA
    <input type="number" id="ROA" /><br> 
    7) Dividend Yield <input type="number" id="DY" /><br>
  8) Debt/Equity
   <input type="number" id="DE" /><br> 
 9)Price/Sales 
  <input type="number" id="PS" /><br> 
  10) Unpledge Promoter Stake
   <input type="number" id="UPS" /><br> 
11) Current Ratio
  <input type="number" id="CR" /><br> 
   <br /> 
   -->
  </form>
</div>
<input id="btnListValues" type="button" value="List values">
<input id="btnResetForm" type="button" value="Reset form">

1 个答案:

答案 0 :(得分:0)

我只是将您的输入字段取消注释为

<div class="ui-widget">
    <form id="frm1">
      <label for="company">Company: </label>
      <input id="company"><br />
      <div class="fields"></div>

  <!-- below decscribed input fields are those ones which i wanted to prefill, rather than creating dynamic fields. but my friend added such kind of function in javascript which firstly creates dynamic input fields and then populate them automatically.....-->



  1) PE Ratio
      <input type="number"  id="PE" /><br>
      2)Price/Book 
       <input type="number"  id="PB" /><br> 
      3)ROCE
      <input type="number" id="ROCE" /><br>
      4) Sales Growth
       <input type="number" id="SG" /> <br> 
      5) NPM 
    <input type="number" id="NPM" /><br>
    6) ROA
      <input type="number" id="ROA" /><br> 
      7) Dividend Yield <input type="number" id="DY" /><br>
    8) Debt/Equity
     <input type="number" id="DE" /><br> 
   9)Price/Sales 
    <input type="number" id="PS" /><br> 
    10) Unpledge Promoter Stake
     <input type="number" id="UPS" /><br> 
  11) Current Ratio
    <input type="number" id="CR" /><br> 
     <br /> 

    </form>
  </div>
  <input id="btnListValues" type="button" value="List values">
  <input id="btnResetForm" type="button" value="Reset form">

然后将所有产生动态字段生成的功能评论为

<script>
  // define the headings here, so we can access it globally
// in the app
let headings = []

// appending the created HTML string to the DOM
/* commented here function initInputs(headingList) {
  jQuery(".fields").append(createInputsHTML(headingList))
} */

// the HTMLT template that is going to be appended
// to the DOM
/* Commented here function createInputsHTML(headingList) {

  let html = ''
  headingList.forEach(heading => {
    if (heading !== 'Company') {
      html += `<label for="${heading}">${heading}: </label>`
      html += `<input id="${heading}">`
      html += '<br>'
    }
  })

  return html
} */

// receiving data
// this data arrives later in the app's lifecycle,
// so it's the best to return a Promise object
// that gets resolved (check JS Promise for more information)
function getJSON() {
  return new Promise(resolve => {
    jQuery.get("https://cors-anywhere.herokuapp.com/www.coasilat.com/wp-content/uploads/2019/06/data-1.txt", function(data) {
      resolve(JSON.parse(data))
    });
  })
}

// processing raw JSON data
function processRawData(data) {
  return new Promise(resolve => {
    const companyData = []
    // creating data array
    // handling multiple sheets
    Object.values(data).forEach((sheet, index) => {
      sheet.forEach((company, i) => {
        companyData.push({ ...company
        })
        // create headings only once
        if (index === 0 && i === 0) {
          Object.keys(company).forEach(item => {
            headings.push(item.trim())
          })
        }
      })
    })
    resolve(companyData)
  })
}

$(async function() {

  let lists = [];

  function initAutocomplete(list) {
    const thisKey = 'Company'
    $("#company").autocomplete('option', 'source', function(request, response) {
      response(
        list.filter(item => {
          if (item[thisKey].toLowerCase().includes(request.term.toLowerCase())) {
            item.label = item[thisKey]
            return item
          }
        })
      )
    })
  }

  $("#company").autocomplete({
    minLength: 3,
    source: lists,
    focus: function(event, ui) {
      // the "species" is constant - it shouldn't be modified
      $("#company").val(ui.item.Company);
      return false;
    },
    select: function(event, ui) {
      // handling n number of fields / columns
      headings.forEach(heading => {
        $('#' + heading).val(ui.item[heading])
      })
      return false;
    }
  });

  // starting data download, processing and usage
  getJSON()
    .then(json => {
      return processRawData(json)
    })
    .then(data => {
      // just so we see what data we are using
      console.log(data)
      // make the processed data accessible globally
      lists = data
      initAutocomplete(lists)
     //commented here initInputs(headings)
    })

});

// this is how you get values form the form
document.getElementById('btnListValues').addEventListener('click', function(e) {
  formGetValues('frm1')
})
// this is how you reset the form
document.getElementById('btnResetForm').addEventListener('click', function(e) {
  formSetValues('frm1', '')
})

function formSetValues(formId, val) {
  const formEl = document.getElementById(formId).elements
  for (let i = 0; i < formEl.length; i++) {
    formEl[i].value = val
  }
}

function formGetValues(formId) {
  const formEl = document.getElementById(formId).elements
  for (let el of formEl) {
    console.log(el.value)
  }
}
  </script>

一切正常。如果您手动创建html字段,那么您的代码是绝对正确的,那么就不需要用于生成动态字段的函数了,我希望这就是您所需要的。