заполнение таблицы в соответствии с выбранными параметрами тега - PullRequest
2 голосов
/ 07 апреля 2020

Javascript новичок здесь, пытающийся учиться на практике, мой вопрос, здесь у меня есть таблица, которая уже заполнена информацией, а под ней находится тег выбора, извлекаемый из URL. Мой вопрос: я хочу снова заполнить таблицу, но с информацией о теге select (в зависимости от того, какой вариант пользователь выбирает из тега select, таблица заполняется этой информацией). вот выберите теги данных

[
    {
        "id": "1111",
        "mygoals": "getmarried",
        "future": "married",

    },
    {
        "id": "2222",
        "mygoals": "getmarried",
        "future": "married",

    },
    {
        "id": "33333",
        "mygoals": "getmarried",
        "future": "married",

    }
]

enter image description here Вот мой код:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
    <style>

    </style>
	
</head>
<body>



<div class="container">

<table class="table table-responsive-sm "> 
  <thead>	
    <tr>
      <th>id</th>
      <th>mygoals</th>
      <th>future</th>
    </tr>
  </thead>
 <tbody id="t">  
  </tbody>

  <thead>
    <tr>
      <th>id</th>
      <th>mygoals</th>
      <th>future</th>
    </tr>
  </thead>
 <tbody id="t2">  
  </tbody>
</table>

<select id="Select" name="name"></select>

</div>

<script>
fetch("https://asdasd.free.beeceptor.com/a", {
    method: "GET",
    headers: {
        "x-api-key": "p*****w"
    }
}).then(res =>{ 
    res.json().then(t => {
        console.log(t);
        var p ="";
        var p2 ="";


        p +="<tr>";
        p += "<td>"+t.id+"</td>";
        p += "<td>"+t.mygoals+"</td>";
        p += "<td>"+t.future+"</td>";
		p2 += "<td>"+t.id+"</td>";
		p2 += "<td>"+t.mygoals+"</td>";
		p2 += "<td>"+t.future+"</td></tr>";

        document.getElementById("t").insertAdjacentHTML("beforeend", p);
		document.getElementById("t2").insertAdjacentHTML("beforeend", p2);
	

    }
  )
}).catch(err => {
      console.log("ERROR: " + err);
});


fetch("https:******.com/", {
    method: "GET",
    headers: {
        "x-api-key": "p*****w"
    }
}).then(res =>{ 
    res.json().then(t => {
	
for (var i = 0; i < t.length; i++) {
    var s = document.getElementById("Select");
    var o = document.createElement("option");
    option.text = t[i].id+ ' ' + t[i].mygoals;
	
    s.add(o);
}
    }
  )
   })
   
   
   
</script>




</body>
</html> 

1 Ответ

1 голос
/ 07 апреля 2020

Если вам нужно заполнить таблицу данными, как только вы получите JSON из своей выборки XHR, вы можете просто перебрать данные и построить строки таблицы.

Я не уверен, что вы имеете в виду , заполняя таблицу выбранными опциями. При необходимости предоставьте полный пример использования, но я понимаю, что вы хотите заполнить таблицу на основе выбора.

См. Пример ниже.

const tableEl = document.querySelector('.table');
const selectEl = document.querySelector('#select');

// Only show the record that matched the selection.
selectEl.addEventListener('change', e => {
  // Or make a call to a different JSON endpoint...
  populateTableWithJSON(tableEl, getJsonData().filter(record => {
    return record.id === e.target.value;
  }));
});

populateTableWithJSON(tableEl, getJsonData());
populateSelectWithJSON(selectEl, getJsonData(), {
  idFn : r => r.id,
  displayFn : r => `${r.id} ${r.mygoals}`
});

function populateSelectWithJSON(select, jsonData, opts={}) {
  emptyElement(select);
  jsonData.forEach((record, index) => {
    let id = opts.idFn != null ? opts.idFn(record) : record.id || index;
    let text = opts.displayFn != null ? opts.displayFn(record) : record.text || '';
    select.appendChild(new Option(text, id));
  });
}

function populateTableWithJSON(table, jsonData) {
  let tbody = table.querySelector('tbody');
  emptyElement(tbody);
  if (jsonData != null && jsonData.length > 0) {
    let headers = table.querySelectorAll('thead > tr th');
    let fields = headers.length
      ? Array.from(headers).map(th => th.textContent)
      : Object.keys(jsonData[0]);
    jsonData.forEach(record => {
      let tr = document.createElement('TR');
      fields.forEach(field => {
        let td = document.createElement('TD');
        td.textContent = record[field];
        tr.appendChild(td);
      });
      tbody.appendChild(tr);
    });
  }
}

function emptyElement(element) {
  while (element.firstChild) {
    element.removeChild(element.firstChild);
  }
}

function getJsonData() {
  return [{
    "id": "1111",
    "mygoals": "getmarried",
    "future": "married",
  }, {
    "id": "2222",
    "mygoals": "getmarried",
    "future": "married",
  }, {
    "id": "33333",
    "mygoals": "getmarried",
    "future": "married",
  }];
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">

<div class="container">
  <table class="table table-responsive-sm ">
    <thead>
      <tr>
        <th>id</th>
        <th>mygoals</th>
        <th>future</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
  <select id="select" name="name"></select>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...