gezer4000 gezer4000 - 3 months ago 8
HTML Question

How would I make this only display one result and add a randomize button?

so I have this code that displays all the objects that fit a variable in a JSON file using Jput.

<script>
$(document).ready(function(){

$("#tbody").jPut({
ajax_url:"valid_data.json",
prepend:true,
name:"tbody_template",
});

});
</script>

<table jput="t_template">
<tbody jput="tbody_template">
<tr>
<td>{{First Name}}</td>
<td>{{Middle Name}}</td>
<td>{{Last Name}}</td>
<td>{{Nationality}}</td>
<td>{{Birthplace}}</td>
<td>{{Age}}</td>
</tr>
</tbody>
</table>

<table>
<tbody id="tbody">
</tbody>
</table>

<script src="jquery-1.12.3.min.js"></script>
<script src="jput.min.js"></script>


Code works fine, (can be seen in action at http://fooda.website/test2.html) but i need a button that when clicked picks a random array and displays only that arrays result.

Javascript knowledge is minimal so not sure how to go about it. Had some previous code that was linked to a CSV file before I was advised to convert to JSON, but i'm lost as to how to implement it in this.

Answer

Not certain about options of .jPut(), though one option would be to set all tr elements style to display:none, then select random tr from table and set that tr to display:block.

According to linked documentation, done option is called when JSON is returned.

<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
  <script src="http://fooda.website/jput.min.js"></script>
</head>

<body>
  <script>
    $(document).ready(function() {
      var tr, button = $("button");
      $("#tbody").jPut({
        ajax_url: "http://fooda.website/valid_data.json",
        prepend: true,
        name: "tbody_template",
        done: function(e) {
          tr = $("table #tbody tr").hide();
          button.removeAttr("disabled")
        }
      });

      button.click(function() {
        tr.hide();
        var rand = Math.floor(Math.random() * tr.length);
        tr.eq(rand).show()
      });
    });
  </script>
  <button disabled>click</button>
  <table jput="t_template" style="display: none;">
    <tbody jput="tbody_template" style="display: none;">
      <tr>
        <td>{{First Name}}</td>
        <td>{{Middle Name}}</td>
        <td>{{Last Name}}</td>
        <td>{{Nationality}}</td>
        <td>{{Birthplace}}</td>
        <td>{{Age}}</td>
      </tr>
    </tbody>
  </table>
  <table>
    <tbody id="tbody">
    </tbody>
  </table>
</body>

</html>

plnkr http://plnkr.co/edit/NURw4djMh9Jp23v3bINP?p=preview