Как сделать так, чтобы значения отображались в полях ввода - PullRequest
1 голос
/ 25 июня 2019

Это мое первое программирование, и я пытаюсь создать функцию на своем веб-сайте, где после выбора элемента в раскрывающемся меню значения, соответствующие этому элементу, будут отображаться в полях ввода, которые я создал. Например, если я выберу «яблоки» в раскрывающемся меню, значения «1.2» и «4.00» появятся в полях ввода «Фунты» и «Стоимость» соответственно.

У меня уже есть код, написанный с использованием HTML и JS для выпадающего меню и полей ввода, и я сохранил данные, соответствующие элементам, в CSV-файле. Прямо сейчас значения отображаются в полях ввода только потому, что я написал код для этого в JS. Есть ли способ для файла HTML прочитать мои данные из файла CSV и отобразить эти данные в моих полях ввода? Ниже то, что я имею до сих пор.

<div id="cs-element">
  <label id="cs-element-label">Elements</label>
</div>

<select onChange="dropdownTip(this.value)" name="search_type" style="margin-right:10px; margin-top:2px;">
 <option selected="selected">Choose Element</option>
 <option>Methane</option>
 <option>Ethane</option>
 <option>Propane</option>
 <option>n-Butane</option>
</select>

<div id="result"></div>

<script type="text/javascript">
 function dropdownTip(value){
   console.log(value);
    document.getElementById("myText").value="190.6";
    document.getElementById("myText1").value="45.99";
    document.getElementById("myText2").value="0.012";
 }
</script>

<div id="cs-tc" class="col-sm-4 text-center">
  <label id="cs-tc-label" class="control-label">Critical Temperature (K)</label>
 <input type="text" id="myText" value=" " class="form-control" name="cs_tc">
</div>

<div id="cs-pc" class="col-sm-4 text-center">
  <label id="cs-pc-label" class="control-label">Critical Pressure (atm)</label>
  <input type="text" id="myText1" value=" " class="form-control" name="cs_pc">
</div>

<div id="cs-acc" class="col-sm-4 text-center">
  <label id="cs-acc-label" class="control-label">Accentric Factor</label>
  <input type="text" id="myText2" value=" " class="form-control" name="cs_acc">
</div>

<script>
$(document).ready(function() {
  $.ajax({
    type: "GET",
    url: "B1_1.csv", //read csv file
    dataType: "text",
    success: function(data) {processData(data);}
   });
});

function processData(allText) {
 var allTextLines = allText.split("/\r\n|\n/");
 var headers = allTextLines[0].split(',');
 var lines = [];

 for (var i=1; i<allTextLines.length; i++) {
  var data = allTextLines[i].split(',');
  if (data.length == headers.length) {

   var tarr = [];
   for (var j=0; j<headers.length; j++) {
    tarr.push(headers[j]+":"+data[j]);
   }
   lines.push(tarr);
  }
 }
}
</script>

Ответы [ 3 ]

0 голосов
/ 25 июня 2019

Взгляните на библиотеку W3.JS . Он имеет компонент с именем W3.data , который позволяет извлекать данные сервера с помощью JavaScript. Может использоваться для чтения содержимого файлов JSON и CSV.

0 голосов
/ 25 июня 2019

Да, конечно, возможно, код, который вы разместили, делает это, я знаю, что изначально это может сбить с толку, но позвольте мне объяснить часть JavaScript ...

<script> 
// in html you use script tag to put javascript code inside and using jquery, you // can easily modify the html page.

$(document).ready(function() { 
// this is a jquery piece of code that is calling an // ajax request

  $.ajax({
    type: "GET",
    url: "B1_1.csv", //read csv file
    dataType: "text",
    success: function(data) {processData(data);}
   });
});

function processData(allText) { 
// a method is a piece of code that you write once because you know that you will // reuse it and it makes the code more readable

 var allTextLines = allText.split("/\r\n|\n/"); 
// split is a method that takes as input a string and (in this case `allText`) //literally split the calling string in n strings storing them in an array. The //strings are splitted by the string you passed as parameter. In this case this //piece of code is simply dividing the entire text in n lines

 var headers = allTextLines[0].split(','); 
// Now is splitting the line number 1 (look for 0-indexed array on google) in many // strings
 var lines = [];

 for (var i=1; i<allTextLines.length; i++) {
 // A for loop is a loop that repeat itself n-times until a condition is no more 
 // satisfied, in this case i has to be smaller than the length of that array.
 // `var i=1` represents the starting point of the index.
 // `i<allTextLines.length` is the condition and `allTextLines.length` returns the 
 // length of the array.
 // In the end `i++` just increment i every time the loop reach the end and restart

  var data = allTextLines[i].split(',');
  if (data.length == headers.length) {
    // an if statement is a piece of code that is executed if and only if a condition 
    // is satisfied.

   var tarr = [];
   for (var j=0; j<headers.length; j++) {
    tarr.push(headers[j]+":"+data[j]);
   }
   lines.push(tarr); // The push method add to an array a new element
  }
 }
}
</script>

Я пытался объяснить как можно лучше (я плохой учитель, так что это тренировка для меня, ахах), я надеюсь, что помог тебе. Если у вас есть какие-либо сомнения, просто спросите, и если вы хотите больше узнать о коде, просто посмотрите учебники в Интернете, потому что их много. Может быть, вы заинтересованы, я узнал javascript от здесь лет назад.

0 голосов
/ 25 июня 2019

Если я понимаю, о чем вы спрашиваете, нет, невозможно прочитать файл из html. Используя форму в формате html, вы можете загружать файлы, но событие обрабатывается JavaScript.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...